'How to return newlines in res.json()
I am creating a React.js app and have the following code that is supposed to send a list of errors to the client if the validation of a registration fails:
return res.status(400).json({success: false, statusCode: 400, message: "The following errors were encountered: "
+ "\\n" + errors.username
+ "\\n" + errors.email
+ "\\n" + errors.password
+ "\\n" + errors.confirmPassword
});
However, this is what I get when logging the response in the browser console on the frontend:
message: "The following errors were encountered: \\nPlease enter a username.\\nPlease enter your email.\\nPassword must be at least 8 characters.\\nPlease confirm your password."
statusCode: 400
success: false
How do I make the "\n" characters actually have newlines in the response?
Solution 1:[1]
I also suspect the answer by Zidaan Hajat is correct, but here's some more info/another solution:
With es6 template strings (which support multiline strings) you can format the code a lot nicer: (the \n are added automatically)
return res.status(400).json({success: false, statusCode: 400, message:
`The following errors were encountered:
${errors.username}
${errors.email}
${errors.password}
${errors.confirmPassword}`
});
When rendering these newlines in React, however (assuming you want to preserve the newlines), they will disappear because \n does not work in HTML.
<ErrorBox>{error.message}</ErrorBox> // will show the message, but without the \n
To output it, I'd go with something like
<ErrorBox>{error.message.split('\n').map(line=>(<>{line}<br /></>))}</ErrorBox> // will show the message, but without the \n
Note that this adds a <br /> at the end of the last line, which you might not want but should easily be able to fix.
Solution 2:[2]
I'm pretty sure you should just be sending the newlines as \n not \\n.
\\n indicates that you want to show the combination of characters themselves, rather than a newline.
Basically the first backslash escapes the second backslash so \\n becomes \n.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Taxel |
| Solution 2 | Siphalor |
