【问题标题】:req.body is empty whith fetch requestreq.body 为空,获取请求
【发布时间】:2019-03-07 19:45:05
【问题描述】:

我正在尝试向我的服务器发出 fetch 请求。 但我一直得到一个空的 req.body。

客户端脚本:

  const form = document.getElementById('form1')

form.addEventListener('submit', (e) => {
    e.preventDefault();
    const formData = new FormData(form);
    const link = formData.get('link');
    var payload = {
        link
    };
    console.log(payload);

    const options = {
        method: "POST",
        body: JSON.stringify(payload),
        headers: {
            'content-type': 'application/json'
        }
    }
    console.log(options);

    fetch('/api/gtmetriks', options)
        .then(response => response.json()).then(result => console.log(result)).catch(err => console.log(err));
})

服务器代码:

const bodyParser = require('body-parser');
const cors = require('cors')
const app = express()
//cors
app.use(cors())

app.use(bodyParser.urlencoded({
    extended: true
}));
// parse application/json
app.use(bodyParser.json())
app.post('/api/gtmetriks', (req, res) => {       
    console.log(req.body);     
})

所以当我发布请求时,我会进入控制台“{}”。 但客户端浏览器中没有错误。

【问题讨论】:

  • `console.log(payload);` 打印的数据是否正确?
  • 这是输出:{method: "POST", body: "{"link":"tesla.com"}", headers: {…}} body: "{"link":"tesla.com"}" headers: content-type: "application/json" __proto__: Object method: "POST" __proto__: Object
  • 能否在console.log() 下的服务器代码中添加res.sendStatus(200);,然后发送请求标头?服务器日志是否显示任何错误?
  • app.post('/api/gtmetriks', (req, res) => { res.send(req.body); }) 如果你这样做会怎样
  • 它在我的电脑上运行良好。

标签: javascript node.js express fetch body-parser


【解决方案1】:

我认为问题在于您使用的是 CORS,但没有指定要发布到哪个 URL。例如,您的客户端是http://localhost:3000,但您的服务器是http://localhost:3001。您将 fetch 发送到 http://localhost:3000/api/gtmetriks 而不是 http://localhost:3001/api/gtmetriks

如果您将 fetch 更改为:

fetch('[YOUR SERVER URL]/api/gtmetriks', options)
  .then(response => response.json())
  .then(result => console.log(result))
  .catch(err => console.log(err));
})

它应该可以工作。

编辑#1:

这段代码使用 React 前端 (3000) 和 Express 后端 (3001) 为我工作:

客户端 app.js

import React, { Component } from 'react';

export default class App extends Component {
  handleSubmit = () => {
    const payload = {
      link: 'http://tesla.com',
    };

    const options = {
      method: 'POST',
      body: JSON.stringify(payload),
      headers: {
        'content-type': 'application/json',
      },
    };

    fetch('http://localhost:3001/api/gtmetriks', options)
      .then(response => response.json())
      .then(result => console.log(result))
      .catch(err => console.log(err));
  };

  render() {
    return (
      <button
        onClick={() => {
          this.handleSubmit();
        }}>
        Click Me
      </button>
    );
  }
}

服务器 server.js

const express = require('express');
const logger = require('morgan');
const cors = require('cors');

const app = express();

//use cors to allow cross-origin resource sharing
app.use(
  cors()
);

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.post('/api/gtmetriks', (req, res) => {
  console.log(req.body);
  res.sendStatus(200);
});

//start your server on port 3001
app.listen(3001, () => {
  console.log('Server Listening on port 3001');
});

【讨论】:

  • 没用:fetch('localhost:5000/api/gtmetriks', options) .then(response =&gt; response.json()) .then(result =&gt; console.log(result)) .catch(err =&gt; console.log(err));
  • 检查编辑。我添加了工作代码并验证了请求正在发送。
  • 我不能在同一个端口上同时使用它们吗?
  • 不,你不能。 React 和 Node 都必须在不同的端口上运行,因为它们都是独立的服务器。 React 是你的前端服务器,Node 是你的后端服务器。
  • @MendiSterenfeld 在您的第一条评论中,您忽略了 http://,这很重要..
猜你喜欢
  • 2017-05-12
  • 2012-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-28
  • 2016-11-20
  • 1970-01-01
相关资源
最近更新 更多