我正在设置一个测试React Web应用程序,以通过Express API连接到我的sql数据库。我正在本地计算机上进行测试,因此我的应用程序在localhost:3000上运行,服务器在localhost:4000上运行。我将package.json中的代理设置为“ http://localhost:4000”。我的应用程序发出的GET请求效果很好,但我的发布请求却没有。
//在我的应用中发出POST请求的函数:
handleSubmit(event) {
fetch("/api/users",
{
method: "POST",
body: JSON.stringify(this.state)
}
)
.then(res => {
console.log(res);
});
}
在我的服务器中处理此路由的功能:
router.post('/users', async (req, res, next) => {
try {
console.log('row is being added...');
let results = await db.insertUser(req);
res.json(results);
} catch(e) {
res.json();
res.sendStatus(500);
}
});
在上一个函数中调用的db.insertUser函数:
testdb.insertUser = (req) => {
return new Promise((resolve, reject) => {
pool.query(`INSERT INTO users SET ?`, req.body, (err, results) => {
if(err) {
return reject(err);
}
return resolve(results);
});
})
}
这是尝试发出POST请求后在浏览器控制台中显示的内容。
Response {type: "basic", url: "http://localhost:3000/api/users", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:3000/api/users"
__proto__: Response
}
这是我在尝试POST之后从服务器收到的错误
(node:85386) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
我不太确定为什么POST请求试图调用localhost:3000而不是GET请求成功调用的代理localhost:4000
更新:
这是我现在在Chrome控制台中遇到的错误
Insert.js:37 POST http://localhost:3000/api/users 500 (Internal Server Error)
_callee$ @ Insert.js:37
tryCatch @ runtime.js:62
invoke @ runtime.js:288
prototype.(anonymous function) @ runtime.js:114
asyncGeneratorStep @ asyncToGenerator.js:3
_next @ asyncToGenerator.js:25
(anonymous) @ asyncToGenerator.js:32
(anonymous) @ asyncToGenerator.js:21
handleSubmit @ Insert.js:50
callCallback @ react-dom.development.js:147
invokeGuardedCallbackDev @ react-dom.development.js:196
invokeGuardedCallback @ react-dom.development.js:250
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:265
executeDispatch @ react-dom.development.js:571
executeDispatchesInOrder @ react-dom.development.js:596
executeDispatchesAndRelease @ react-dom.development.js:695
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:704
forEachAccumulated @ react-dom.development.js:676
runEventsInBatch @ react-dom.development.js:844
runExtractedEventsInBatch @ react-dom.development.js:852
handleTopLevel @ react-dom.development.js:5030
batchedUpdates$1 @ react-dom.development.js:21425
batchedUpdates @ react-dom.development.js:2247
dispatchEvent @ react-dom.development.js:5110
(anonymous) @ react-dom.development.js:21482
unstable_runWithPriority @ scheduler.development.js:255
interactiveUpdates$1 @ react-dom.development.js:21481
interactiveUpdates @ react-dom.development.js:2268
dispatchInteractiveEvent @ react-dom.development.js:5086