req.body为空,是否获取请求

时间:2019-03-07 19:45:06

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

我正在尝试对我的服务器进行提取请求。 但我不断收到一个空的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);     
})

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

1 个答案:

答案 0 :(得分:-1)

我认为问题是您正在使用CORS,但未指定要发布到的URL。例如,您的客户端为http://localhost:3000,而服务器为http://localhost:3001。您正在将提取内容发送到http://localhost:3000/api/gtmetriks而不是http://localhost:3001/api/gtmetriks

如果您将抓取更改为:

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');
});