首页 > 解决方案 > 如何正确执行从 react-native 到 express.js 和 mySQL 后端的 POST 请求

问题描述

我按照这一系列教程第一部分第二部分的建议,使用 mySql 数据库创建了 express.js 后端。使用 Postman 测试了所有路线,并且已经可以正常工作。

然后,使用 react-native,我尝试了一个简单的 Get 请求来从数据库中的表中获取数据:

<Button title='Test MySQL Connection' 
   onPress = {()=>{
     fetch('http://my_laptop_IP:3000/users')
     .then(response => response.json())
     .then(users => alert(users))}}
 />

这很容易正常工作。

但是,当我尝试使用 Post 在表中插入一行时,它失败了:

<Button title='Test MySQL Connection' 
   onPress={()=>{    
     fetch('http://my_laptop_IP:3000/users', {
       method: 'POST',
       headers: {       
         Accept: 'application/x-www-form-urlencoded',
         'Content-Type': 'application/x-www-form-urlencoded',
       },
       body: JSON.stringify({
         first_name:'Cell',
         last_name: 'First_form',
       })
     })
     .then((response) => response.json())
     .then((response) => {
        alert(response);
      })
     .catch((error) => alert('Error ' + error));
    }}
 />

express 后端的错误截图如下: 在此处输入图像描述

这显示在我的虚拟设备模拟器中:

在此处输入图像描述

尝试像这样更改获取请求的标头部分:

headers: {
   Accept: 'application/json',
   'Content-Type': 'application/json',
},

还是没有运气。。

标签: javascriptmysqlreact-nativeexpressfetch-api

解决方案


如果您将 JSON 作为请求正文传递,则可以使用

fetch("http://localhost:3000/users", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        first_name: "Cell",
        last_name: "First_form"
      })
    })
      .then(response => response.json())
      .then(response => {
        console.log(response)
      })
      .catch(error => alert("Error " + error))

此外,您可能需要将 cors 模块添加到您的 server.js

var express = require("express");
var cors = require('cors');


  app = express(),
  
  port = process.env.PORT || 3000,
  bodyParser = require("body-parser"),
  controller = require("./controller");

app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var routes = require("./routes");
routes(app);

app.listen(port);
console.log("Learn Node JS With Kiddy, RESTful API server started on: " + port);


推荐阅读