【问题标题】:How to send the request from react native to express js?如何将react native的请求发送到express js?
【发布时间】:2021-04-10 00:25:29
【问题描述】:

我现在担心将请求正文从我的 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-native express


    【解决方案1】:

    正确的语法是

    客户端

    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 });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-27
      • 2018-02-10
      • 1970-01-01
      • 2021-03-09
      • 1970-01-01
      • 2020-03-24
      • 2020-08-14
      • 2021-11-02
      相关资源
      最近更新 更多