我正在使用express和nodejs,遇到麻烦,然后方法记录了一个未决的Promise。
edit().then(data => console.log(data));
这是编辑功能。
async function edit(data, id) {
let response = await fetch(config_url+'/subscriber/' + id, {
headers : { "content-type" : "application/json; charset=UTF-8"},
method: 'PUT',
body: JSON.stringify(data)
});
let ret = await repsonse.json();
return ret;
}
其余api是express js。
Subscriber.edit = function (name, email, id, result) {
sql.query("UPDATE subscribers SET name=?, email=? WHERE id = ?", [name, email, id], function (err, res) {
if (err) {
console.log("error: ", err);
result(null, err);
} else {
console.log(res);
result(res);
}
});
};
数据库中的数据已更改,但在邮递员的res.send()行“订户已成功更改”下方。
exports.edit_subscriber = function (req, res) {
console.log(req.params);
console.log(req);
console.log(res);
Subscriber.edit(req.body.name, req.body.email, req.params.id, function(err, subscriber) {
if (err) {
res.sendStatus(err);
}
res.send({ message: 'Subscriber succesfully edited'});
});
};
再次说明为什么我自己的异步函数返回的Promise尚未解析,并在chrome控制台中处于待处理状态。
表达错误
'access-control-allow-origin': [ 'Access-Control-Allow-Origin', '*' ]
}
}
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '(Rows matched: 1 Changed: 1 Warnings: 0',
protocol41: true,
changedRows: 1
}
/Users/[classified]/repos/[classified]]/node_modules/mysql/lib/protocol/Parser.js:437
throw err; // Rethrow non-MySQL errors
^
RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '(Rows matched: 1 Changed: 1 Warnings: 0',
protocol41: true,
changedRows: 1
}
at ServerResponse.writeHead (_http_server.js:241:11)
at ServerResponse._implicitHeader (_http_server.js:232:8)
at write_ (_http_outgoing.js:607:9)
at ServerResponse.end (_http_outgoing.js:717:5)
答案 0 :(得分:0)
您必须对res.send(JSON.stringify(json))
exports.edit_subscriber = function (req, res) {
...
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ message: 'Subscriber succesfully edited' }));
};
在下面的代码中,您还将参数错误地传递给了回调。第一个参数是err
,第二个参数是result
。它没有正确通过。
Subscriber.edit = function (name, email, id, resultCallBack) {
sql.query("UPDATE subscribers SET name=?, email=? WHERE id = ?", [name, email, id], function (err, res) {
if (err) {
console.log("error: ", err);
resultCallBack(err);
} else {
console.log(res);
resultCallBack(null, res);
}
});
};
res.sendStatus
也仅接受状态码。
res.sendStatus(400).send(JSON.stringify{message: 'error occured'});
希望这会有所帮助