【问题标题】:How to extract req.body on the server side (I'm using fetch)?如何在服务器端提取 req.body(我正在使用 fetch)?
【发布时间】: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


【解决方案1】:

在 Express 4.16 中不再需要 body-parser 模块。获得身体所需的只是:

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

在 fetch 中使用 "Content-type": "application/x-www-form-urlencoded" 否则 CORS 将发送预检并给您带来困难。 (有关此 google CORS 简单请求要求的更多信息)。

【讨论】:

    【解决方案2】:

    默认情况下,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 等结构化数据格式通常比使用纯文本格式更好。

    【讨论】:

      【解决方案3】:

      尝试以下方法:

      1. 在 server.js 文件中使用正文解析器。

      2. 发送post请求为content-typejson如下,

        headers: { Content-Type: application/json }

      body 应该是 JSON

      body: {"color":"ORANGE"}

      1. 在你的路线上打印

        console.log(req.body.color)

      【讨论】:

        【解决方案4】:

        正如 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));
        

        所以您的响应中没有正文对象,只有一个 json 对象,即您的正文。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-19
          • 2021-10-31
          • 2023-02-25
          • 2013-05-08
          • 2020-04-03
          • 2021-12-11
          相关资源
          最近更新 更多