我正在将一些数据从我的 ReactJS 前端应用程序发送到我的节点/快速后端,但是,每当我发送数据时,我都会收到标题中提到的错误消息。
这是我的 ReactJS 代码:
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>
);
}
}
(对不起,如果代码很多,我尽可能地缩短了它,但我不确定哪些部分与问题相关)。
以下是我如何在节点中接收数据以及如何将部分数据保存到我的数据库中:
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!');
});
});
这就是它变得奇怪的地方。该应用程序运行良好,直到我插入upload.single("file")
,但是,我似乎无法弄清楚原因。当我只有文本输入时,我没有任何问题,即使当我创建FormData()
等时,它仍然可以正常工作,直到我实现它。
我尝试查找它并实施此处发布的答案,但是,似乎没有任何帮助。
在屏幕上,我收到以下错误消息:Unhandled Rejection (SyntaxError): Unexpected token P in JSON at position 0
当我检查终端时,我收到标题中提到的错误消息。我尝试删除内容标题(不确定那会做什么,但我遵循的实现文件上传的教程没有使用内容标题,这就是我尝试删除它们的原因。有谁知道如何解决这个错误?
编辑:终端中的错误消息还包含ECONNRESET
. 我按照终端https://nodejs.org/api/errors.html#errors_common_system_errors 中的链接进行操作,但我仍然不确定如何解决该问题。
我建议您将所有字段附加到FormData
对象,并且不要将提交的数据转换为 json 字符串:
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);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句