javascript - 如何正确执行从 react-native 到 express.js 和 mySQL 后端的 POST 请求
问题描述
我按照这一系列教程第一部分和第二部分的建议,使用 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));
}}
/>
这显示在我的虚拟设备模拟器中:
尝试像这样更改获取请求的标头部分:
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
还是没有运气。。
解决方案
如果您将 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);
推荐阅读
- python-3.x - pytest 为所有测试存根方法
- python - Python - 正确的包管理导致代码问题?曾经工作的代码现在出错了
- draftjs - 如何让 Draft.js 编辑器在光标后显示占位符文本?
- broadcastreceiver - Android / kotlin如何在不得不停止请求许可后恢复执行
- bash - 二维数组文件拆分与检索 | 重击
- javascript - 如何从对象数组中删除重复对象但具有两个唯一键
- c++ - 流畅的线条opengl
- ios - 将时间转换为 GMT,然后将时间戳上传到 Firebase (Swift)
- sql - AWS Glue 总是向 SQL Server 发送“select * ....”,为什么以及如何更改它?
- html - 如何从 Facebook 浏览器共享包含网页报价的链接到 Facebook 帖子?