I'm sending some data from my ReactJS front-end application to my node/express backend, however, whenever I send the data, I get the error message mentioned in the title.
This is my ReactJS code:
class App extends React.Component {
constructor(props) {
super(props);
//states and binding functions
}
fetchData () {
fetch('/users')
.then(res => res.json())
.then(users => this.setState({users}));
}
addUser (event) {
let fileData = new FormData();
fileData.append("file", this.state.filesToBeSent);
axios.post('adduser',
querystring.stringify({
entry: this.state.currname,
passwrd: this.state.currpasswrd,
fileData : fileData
})
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
componentDidMount() {
this.fetchData();
}
render() {
return (
<div className="App">
<form onSubmit={this.addUser} encType="multipart/form-data">
<label>New username:</label>
<input value={this.state.currname} onChange={this.handleChange}></input>
<input value={this.state.currpasswrd} onChange={this.handlePassword} />
<input type="file" name="file" onChange={this.handleFile} />
<button type="submit" >Add</button>
</form>
<h1>Current Users: </h1>
{this.state.users.map((name, n) =>
//map through user-array and display names
)}
</ul>
</div>
);
}
}
(Sorry if it's a lot of code, I shortened it as much as possible but I wasn't sure which parts would be relevant to the question).
Here is how I receive the data in node and how I save parts of it to my db:
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./uploads/");
},
filename: (req, file, cb) => {
const newFilename = `${uuidv4()}${path.extname(file.originalname)}`;
cb(null, newFilename);
},
})
const upload = multer({ storage });
router.post("/", upload.single("file"), (req, res) => {
res.send(req.file + " and exit.");
var newUser = new Todo();
newUser.username = req.body.entry;
newUser.passwrd = req.body.passwrd;
newUser.save(function (err) {
if(err)
res.send(err);
res.send('User added successfully!');
});
});
This is where it gets weird. The application works perfectly, until I insert upload.single("file")
, however, I couldn't seem to figure out why. I didn't have any problems when I just had text inputs, even when I created the FormData()
etc. it still worked fine until I implemented that.
I tried looking it up and to implement answers posted on here, however, nothing seems to help.
On the screen I get the following error message: Unhandled Rejection (SyntaxError): Unexpected token P in JSON at position 0
When I check the terminal I receive the error message mentioned in the title. I tried removing the content-headers (not sure what that would do, but the tutorial I was following to implement the file upload did not use content-headers, that's why I tried to remove them. Does anyone know how to fix this error?
Edit: The error message in the terminal also contains ECONNRESET
. I followed the link in the terminal https://nodejs.org/api/errors.html#errors_common_system_errors but I'm still not sure how I can fix that.
I suggest you to append all fields to FormData
object, and do not convert the submitted data to json string:
let fileData = new FormData();
fileData.append("entry", this.state.currname);
fileData.append("passwrd", this.state.currpasswrd);
fileData.append("file", this.state.filesToBeSent);
axios.post('adduser', fileData)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.