首页 > 解决方案 > app.use(express.json) 在返回空对象的请求后不起作用

问题描述

const express = require('express');
          app = express();
          PORT = 3030;
    
    app.use(express.json());
    app.use(express.urlencoded({ extended: false }));
    
    app.get("/", (req, res) => {
      res.send('Hello World')
    });
    
    app.post('/', (req, res) => {
      console.log(req.body);
      res.json(req.body)
    })
    
    app.listen(PORT, err => {
      if(err) {
        return console.log('ERROR', err);
      }
    
      console.log(`Listening on port ${PORT}, http://localhost:${PORT}/`)
    });

我正在使用 Postman 来测试它,这就是我正在使用的。

我正在使用表单数据:

{编号:123,新:新}

我试过使用 body-parser 但它已经被贬值了。

我正在使用快递“^4.17.1”

我只是想知道它是否是本地的东西可能会导致问题,因为我已经查找了几个教程并且他们没有这个问题。

邮递员详情

我也尝试过使用 fetch 发出请求:

let options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      number: '123',
      new: 'new'
    })
  }
  fetch('http://localhost:3030/', options)
    .then(response => response.json())
    .then(data => console.log(data));

我得到的只是:

test.html:61 POST http://localhost:3030/ net::ERR_CONNECTION_REFUSED

Uncaught (in promise) TypeError: Failed to fetch

标签: javascriptnode.jsexpress

解决方案


您的邮递员图像显示form-data(可能是multipart/form-data)作为内容类型,这不是您的任何一个中间件处理程序都知道的内容。

express.json()解析 JSON 内容类型,如application/json.

express.urlencoded()解析 URl 编码的内容类型,如application/x-www-form-urlencoded.

人们经常使用multer进行解析multipart/form-data,但如果这些数据只是简单的表单数据(名称/值对),那么您应该将其编码为application/x-www-form-urlencoded或者application/json而不是部署 multer。Multer 通常在您有文件上传时使用,这multipart/form-data是必要的选择。


推荐阅读