【问题标题】:Why I'm getting empty object when doing post request为什么我在进行发布请求时得到空对象
【发布时间】:2019-11-02 02:59:36
【问题描述】:

我尝试向其他 localhost 服务器发送请求(因为在项目中我使用的是 webpack,但我不知道如何管理默认 webpack 服务器)。

这是我的发帖请求文件。

    btn_bag[0].addEventListener('click', (e) => {
      e.preventDefault(),
      fetch('http://localhost:3000/get', {
        method:'POST',
        headers: {
          'Content-Type':'application/json;charset=utf-8'
        },
        body: JSON.stringify(order_pizza)
    })
      .then(console.log(order_pizza))
    })

这是我的服务器,当我单击按钮时,服务器中的控制台记录 {},当“order_pizza”(我发布的变量)不为空时。是什么问题,请帮忙寻找解决办法。


    const express = require('express');
    const app = express();
    const bodyParser = require('body-parser');
    const fs = require('fs');
    const cors = require('cors');
    const urlencodedParser = bodyParser.urlencoded({extended: false})

    app.get('/', (req, res) => {
        res.send('hello')
    })
    app.use(cors({
        allowedOrigins: [
            'http://localhost:9000'
        ]
    }));
    app.get('/get', (req,res) => {
        console.log(req.body)
        res.send('get')})

    app.post('/get',urlencodedParser, (req,res) => {
    console.log(req.body)})

    app.listen(3000)

【问题讨论】:

    标签: javascript node.js express webpack


    【解决方案1】:

    在您的前端,不要对正文进行字符串化,将其作为对象发送,如下所示。 还将目标端点更改为/post

      btn_bag[0].addEventListener('click', (e) => {
      e.preventDefault(),
      fetch('http://localhost:3000/post', {
        method:'POST',
        headers: {
          'Content-Type':'application/json;charset=utf-8'
        },
        body: {order_pizza}
    })
      .then(console.log(order_pizza))
    })
    

    在您的服务器中,将端点 URL 更改为 /post 以使其有意义。 并访问请求正文,如下所示。 而且您不需要在此端点上使用urlencodedParser

      app.post('/post', (req,res) => {
       console.log(req.body)})
      })
    

    同时将 body-parser 应用到您的 express 应用,如下所示

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: false}));
    

    【讨论】:

      【解决方案2】:

      试试这个

      const express = require('express');
      
      const bodyParser = require('body-parser');
      
      const app = express();
      
      app.use(bodyParser.json());
      
      app.use(bodyParser.urlencoded({extended: true}));
      

      您不必在 app.post api 调用中传递 urlencodedParser,希望对您有所帮助

      【讨论】:

        猜你喜欢
        • 2020-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        • 2021-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多