简体   繁体   English

如何正确执行从 react-native 到 express.js 和 mySQL 后端的 POST 请求

[英]How to properly do a POST request from react-native to express.js & mySQL backend

I created an express.js backend with mySql database as suggested by these series of tutorial first part here and second part here .我按照本系列教程第一部分第二部分的建议,使用 mySql 数据库创建了一个 express.js 后端。 Tested all the routes using Postman and already works fine.使用 Postman 测试了所有路线,并且已经正常工作。

Then, using react-native, i tried a simple Get request to fetch data from a table in the database:然后,使用 react-native,我尝试了一个简单的 Get 请求来从数据库中的表中获取数据:

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

This easily works fine.这很容易正常工作。

However, when i tried to insert a row in the table using Post, it failed:但是,当我尝试使用 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));
    }}
 />

Error screenshot for the express backend as follows: express 后端的错误截图如下: 在此处输入图像描述

And this is displayed in my virtual device emulator:这显示在我的虚拟设备模拟器中:

在此处输入图像描述

have tried to change the header part of the fetch request like this:已尝试更改获取请求的 header 部分,如下所示:

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

still no luck..还是没有运气。。

If you are passing JSON as request body you can use如果您将 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))

Also you might need to add cors module to your server.js此外,您可能需要将 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM