[英]res.send is not returning the expected data: JavaScript, Express, Node?
I have a post request that submits a patient name and the server is supposed to give me back patient_id
in response. 我有一个提交病人姓名的帖子请求,服务器应该给我发回
patient_id
作为响应。 I get a 200 response back to the client however I don't get the patient_id
back which is what I need. 我收到200
patient_id
回复给客户,但是我没有找回patient_id
。 When I console log on the server i can see patient.id
is generated and there are no errors either. 当我在服务器上控制台登录时,我可以看到生成了
patient.id
,也没有错误。 Wonder if there is something I am missing? 想知道我是否缺少什么?
Response -
body: (...), bodyUsed: false, headers: Headers {}, ok: true, redirected: false, status: 200, statusText: "OK", type: "basic", url: "http://localhost:4000/patient/add"
//client side post
handleSubmit(e) {
e.preventDefault();
const postUrl = '/patient/add';
fetch(postUrl, {
method: 'POST',
headers: {'Content-Type': 'text/plain'},
body: this.state.patientName
})
.then(response=> {
if (!response.ok) console.log('failed', response);
else console.log(response);
});
}
this.app.post('/patient/add', bodyParser.text(),
this.route_post_patient_add.bind(this));
async route_post_patient_add(req, res) {
/** @type {string} */
const body = req.body;
if (body === undefined) {
logger.warning('Set room patient failed, body missing');
res.sendStatus(400);
return;
}
if (body === "") {
logger.warning(' body is empty');
res.sendStatus(400);
return;
}
try {
const patient_id = await this.save_patient(body);
res.send(patient_id);
console.log(patient_id); //logs the id that is generated
}
catch (err) {
logger.error('Set patient failed, internal error', { err });
res.sendStatus(500);
}
}
The response
object in fetch
is not the raw body. fetch
的response
对象不是原始主体。
You have to call a function and resolve a promise to get the data. 您必须调用一个函数并解析一个诺言以获取数据。
For example: 例如:
fetch("foo")
.then(parse_body)
.then(log_data);
function parse_body(response) {
return response.text();
}
function log_data(response_text) {
console.log(response_text);
}
Further reading: MDN: Using Fetch 进一步阅读: MDN:使用提取
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.