为什么API不能从React客户端获取POST的body?

问题描述 投票:0回答:1

后台使用express.js的API代码。

var express = require('express')
var bodyParser = require('body-parser')

var app = express()
var port = 5000;

var urlencodedParser = bodyParser.urlencoded({extended:true})
app.use(urlencodedParser);

app.get('/', urlencodedParser, function (req, res) {
  console.log( req.body );
  res.send('welcome, Get is working')
})

app.post('/', urlencodedParser, function (req, res) {
  console.log( req.body );
  res.send('welcome, Post is working...\n' + req.body.name)
})

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

客户端的React代码

import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";

class App extends Component {
    constructor(props) {
        super(props);
        this.state = { apiResponse: "" };
        console.log('constructor called');
    }

    callAPI() {
        console.log('callAPI called');

        let formData = new FormData();
        formData.append('name', 'myname');
        fetch(
          "/", {
            body: formData,
            method: 'post',
            header: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }   
          }   
        )   
            .then(res => res.text())
            .then(data => this.setState({ apiResponse: data })) 
    }   

    componentDidMount() {
        console.log('componentDidMount called');
        this.callAPI();
    }   

    render() {
        console.log('render called');
        return (
            <div className="App">
                <header className="App-header">
                    <img src={logo} className="App-logo" alt="logo" />
                    <h1 className="App-title">Welcome to React</h1>
                </header>
                <p className="App-intro">{this.state.apiResponse}</p>
            </div>
        );
    }
}

export default App;

软件包.json

{
  "name": "my_react_app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.4.2",
    "react-dom": "^16.4.2",
    "react-scripts": "1.1.5"
  },  
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },  
  "proxy": "http://localhost:5000"
}

浏览器显示 "welcome, Post is working... undefined","console.log in api "没有正文,只有"{}"。

当我输入命令 "curl -d "name=myname" http:/localhost:5000,客户端显示 "欢迎,Post is working...","console.log in api "显示"{ name: 'myname'}"。看起来工作正常。

我觉得后台的API端没有问题,但是搞不清楚客户端的问题在哪里。

请大家帮帮我。

reactjs api express post fetch
1个回答
0
投票

你需要设置contentType multipartform-data。

 header: {
          'Content-Type': 'multipart/form-data'
        } 
© www.soinside.com 2019 - 2024. All rights reserved.