【问题标题】:How to properly do a POST request from react-native to express.js & mySQL backend如何正确执行从 react-native 到 express.js 和 mySQL 后端的 POST 请求
【发布时间】:2020-01-24 03:10:23
【问题描述】:

按照这一系列教程first part heresecond part here 的建议,我使用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',
},

还是没有运气..

【问题讨论】:

  • 看起来服务器无法解析正文参数。你能把服务器代码贴在你阅读名字和姓氏的地方吗
  • @nithin 我有 5 个服务器文件:server.js、routes.js、controller.js、res.js、conn.js。这是来自 controller.js 的 sn-p:exports.createUsers = function(req, res) { var first_name = req.body.first_name; var last_name = req.body.last_name; connection.query('INSERT INTO person (first_name, last_name) values (?,?)', [ first_name, last_name ], function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok("Berhasil menambahkan user!", res) } }); };
  • @nithin 完整的源代码可以在我原来的问题中的教程链接中找到(抱歉是印尼语)
  • 我相信,访问req.body需要添加body-parser中间件来表达
  • @nithin 你能发布语法吗?或者也许是一个样本的答案,好吗?

标签: javascript mysql react-native express fetch-api


【解决方案1】:

如果您将 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多