首页 > 解决方案 > 如何将react native的请求发送到express js?

问题描述

我现在担心将请求正文从我的 react native 发送到后端 express JS。按下或单击按钮后,来自我的服务器的日志显示未定义。所有 get 方法都在工作,除了 post 方法。我阅读了很多关于这方面的文件。

  1. https://dev.to/saulojoab/how-to-get-data-from-an-mysql-database-in-react-native-53a4
  2. https://reactnativecode.com/fetch-api-tutorial-insert-into-mysql-php/

导入模块:

const express = require('express');
var cors = require('cors')
const bodyParser = require('body-parser');
const mysql = require('mysql');
const app = express();

app.use(express.json());

app.use(express.urlencoded({
  extended: true
}));


var cors = require('cors');

app.use(cors());

邮寄方式:

app.post('/api/new_readings/', function (req, res) {

  connection.getConnection(function (err, connection) {

    console.log(req.body.name);

   
  });
});

提交处理程序:

 fetch('http://myippppp:3000/api/new_readings/', {
        method: 'POST',
        headers: 
            {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
        body: { 
          "name": "x",
          "email": "a",
          "password": "1234"
        }
      })
      .then(response => response.json()) 
      .then(serverResponse => console.warn(serverResponse))

错误:

错误

希望有人对此有所帮助。

标签: react-nativeexpress

解决方案


正确的语法是

客户端

fetch('http://myippppp:3000/api/new_readings/', {
        method: 'POST',
        headers: 
            {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
        body: JSON.stringify({ 
          "name": "x",
          "email": "a",
          "password": "1234"
        }) // need to use JSON.stringify
      })
      .then(response => response.json()) 
      .then(serverResponse => console.warn(serverResponse))

服务器端

app.post('/api/new_readings/', function (req, res) {

    console.log(req.body.name);

    return res.json({ ok: true });
});

推荐阅读