Как правильно сделать POST-запрос от реактивного-родного к express.js и бэкэнду mySQL - PullRequest
0 голосов
/ 24 сентября 2019

Я создал бэкэнд express.js с базой данных mySql, как предлагается в следующих сериях урока первая часть здесь и вторая часть здесь .Протестировал все маршруты с помощью Postman и уже отлично работает.

Затем, используя реактивный-родной, я попробовал простой запрос 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));
    }}
 />

Снимок экрана ошибки для экспресс-бэкэнда следующим образом: enter image description here

И это отображается в моем эмуляторе виртуального устройства:

enter image description here

попытались изменить часть заголовказапрос на получение вот так:

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

все равно не повезло ..

1 Ответ

0 голосов
/ 24 сентября 2019

Если вы передаете 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 на ваш сервер.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);
...