【发布时间】:2020-02-15 09:39:51
【问题描述】:
我正在制作一个由单独的前端和后端组成的项目。从前端,我通过 fetch 发出一个 POST 请求,该请求应将字符串“ORANGE”发送到后端,然后后端应将其记录到控制台。我无法让后端控制台记录字符串。我在 devtools 中查看了请求,字符串“ORANGE”被埋在“请求有效负载”下。请求本身发送正常。我如何实际访问字符串以便我可以用它做事? (例如,存储在数据库中)
//FRONTEND
const commentForm = document.getElementById("editform");
commentForm.addEventListener('submit', function(e) {
e.preventDefault();
fetch('http://localhost:3000/posts/:id', {
mode: 'cors',
method: 'post',
headers: {
"Content-type": "text/plain;charset=UTF-8"
},
body: "ORANGE"
}).then(function(response) {
if (response.ok) {
console.log("response.ok was true: "+ response)
} else {
let error = new Error(response.statusText)
error.response = response
throw error
}
})
});
//BACKEND
router.post('/posts/:id', function(req, res, next) {
console.log('What do I put here to get ORANGE logged?!')
//On the server side I tried some console.log tests.
//console.log("req is " + req); //req is [object Object]
//console.log("type of req is " + typeof req); //type of req is object
//console.log(JSON.parse(req)); //SyntaxError: unexpected token o in JSON at position 1
res.send('whatever. I want ORANGE.')
}
【问题讨论】:
-
console.log(req.body)呢?? -
req.body 未定义
-
Express 曾经在请求上有一个 rawBody 属性,但现在已经删除了,现在所有请求正文都应该是 JSON 格式。如果要发送纯文本正文,则必须实现自己的中间件,如以下答案所述:stackoverflow.com/a/12345876/2444210
-
您需要将localhost:3000/posts/:id 中的 :id 替换为实际的 id。
-
@jperl 一旦路由对该参数执行任何操作,这将是必要的,但这并不能阻止正文可用;它只会将 req.params.id 绑定到字符串
:id。
标签: javascript node.js express