我正在制作一个包含独立的前端和后端的项目。从前端,我通过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.')
}
答案 0 :(得分:0)
尝试以下操作:
在server.js文件中使用正文解析器。
以content-type
和json
的形式发送发帖请求,如下所示,
headers: { Content-Type: application/json }
且正文应为JSON
body: {"color":"ORANGE"}
在您的路线中只需打印
console.log(req.body.color)
答案 1 :(得分:0)
Express默认情况下不会处理请求的正文。您需要显式加载模块。
由于您使用的是纯文本,因此可以使用body-parser模块。这将在请求上创建一个body
属性:
const bodyParser = require('body-parser');
router.use(bodyParser.text({type: 'text/plain'}))
router.post('/posts/:id', function(req, res, next) {
console.log(req.body);
res.send('Response')
});
但是请注意,通常最好使用JSON之类的结构化数据格式,而不是纯文本。
答案 2 :(得分:0)
在Express 4.16中,不再需要主体解析器模块。您需要得到的所有身体就是:
"Content-type": "application/x-www-form-urlencoded"
在抓取过程中使用touchButton(_:)
,否则CORS会发送预检并给您带来麻烦。 (有关此Google CORS简单请求要求的更多信息)。
答案 3 :(得分:-1)
如fetch()的documentation中所述:
这只是一个HTTP响应,而不是实际的JSON。提取JSON正文 响应中的内容,我们使用json()方法(在Body mixin上定义, 这是由Request和Response对象实现的。)
const response = await fetch('http://example.com/movies.json');
const myJson = await response.json();
console.log(JSON.stringify(myJson));
因此您的响应中没有body对象,只有json对象即您的身体。