Search code examples
javascriptencodingaxiosline-breakstemplate-literals

JavaScript line break encoding in template literals


In template literals, line breaks can be represented with \n or with literal line breaks in the string. According to documentation and from printing to console, there is no difference between these two methods.

However, when working with Axios, I sent a string over with with the \n in the data field of POST. The server interpreted this request incorrectly and merged the lines in the string. When I changed all the \n characters with literal line breaks in the string, the server interpreted the request as expected. What is going on here? Is there a difference in encoding between the two methods?

// this works
    await axios.post(`${myURL}/`, {
            password: `${username}@${server}
            ${password}`
        });

// this doesn't work
    await axios.post(`${myURL}/`, {
            password: `${username}@${server}\n${password}`
        });

Solution

  • Is there a difference in encoding between the two methods?

    Yes, your first code also includes a number of non-newline spaces between the server and the password:

                ${password}`
    ^^^^^^^^^^^^
    

    To make them identical, add spaces after the \n, something like:

    await axios.post(`${myURL}/`, {
            password: `${username}@${server}\n             ${password}`
        });
    

    (you might only need one additional space after the \n for it to be parsed properly - experiment a bit)