如何在服务器端提取 req.body(我正在使用 fetch)?

我正在制作一个由单独的前端和后端组成的项目。从前端,我通过 fetch 发出一个 POST 请求,该请求应该向后端发送一个字符串“ORANGE”,然后后端应该将其记录到控制台。我无法让后端控制台记录字符串。我查看了 devtools 中的请求,字符串“ORANGE”被埋在“Request payload”下。请求本身发送正常。我如何实际访问字符串以便我可以用它做事?(例如,存储在数据库中)


//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.')

}


慕哥9229398
浏览 346回答 3
3回答

红颜莎娜

默认情况下,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)而不是纯文本。

摇曳的蔷薇

尝试以下操作:在 server.js 文件中使用正文解析器。发送POST请求作为content-type为json如下,headers: { Content-Type: application/json }和 body 应该是一个 JSONbody: {"color":"ORANGE"}在您的路线中只需打印console.log(req.body.color)

互换的青春

在 Express 4.16 中,不再需要 body-parser 模块。获得身体所需要的只是:app.use(express.urlencoded({ extended: true }));app.use(express.json());"Content-type": "application/x-www-form-urlencoded"在 fetch 中使用,否则 CORS 会发送预检并给您带来困难。(有关此 google CORS 简单请求要求的更多信息)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript