我目前正在使用 Deno 开发概念验证的REST api应用,而我的 post方法遇到了问题(getAll等了)。我的请求的正文不包含因失眠而发送的数据。
我的方法:
addQuote: async ({ request, response }: { request: any; response: any }) => {
const body = await request.body();
if (!request.hasBody) {
response.status = 400;
response.body = { message: "No data provided" };
return;
}
let newQuote: Quote = {
id: v4.generate(),
philosophy: body.value.philosophy,
author: body.value.author,
quote: body.value.quote,
};
quotes.push(newQuote);
response.body = newQuote;
},
请求:
响应:
我将Content-Type - application/json
放在标题中。
如果我只返回body.value
,则为空。
感谢帮助!
答案 0 :(得分:3)
由于值类型是可以保证的,我们必须在访问值之前先进行解析。
尝试一下:
addQuote: async ({ request, response }: { request: any; response: any }) => {
const body = await request.body(); //Returns { type: "json", value: Promise { <pending> } }
if (!request.hasBody) {
response.status = 400;
response.body = { message: "No data provided" };
return;
}
const values = await body.value;
let newQuote: Quote = {
id: v4.generate(),
philosophy: values.philosophy,
author: values.author,
quote: values.quote,
};
quotes.push(newQuote);
response.body = newQuote;
}