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

后台使用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端没有问题,但是搞不清楚客户端的问题在哪里。

请大家帮帮我。

解决方案:

你需要设置contentType multipartform-data。

 header: {
          'Content-Type': 'multipart/form-data'
        } 

本文来自投稿,不代表实战宝典立场,如若转载,请注明出处:https://www.shizhanbaodian.com/40684.html

(0)
上一篇 16小时前
下一篇 15小时前

相关推荐

发表评论

登录后才能评论