react-native - 如何将react native的请求发送到express js?
问题描述
我现在担心将请求正文从我的 react native 发送到后端 express JS。按下或单击按钮后,来自我的服务器的日志显示未定义。所有 get 方法都在工作,除了 post 方法。我阅读了很多关于这方面的文件。
- https://dev.to/saulojoab/how-to-get-data-from-an-mysql-database-in-react-native-53a4
- 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))
错误:
希望有人对此有所帮助。
解决方案
正确的语法是
客户端
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 });
});
推荐阅读
- azure - Updating Two Databases Via A Load Balancer?
- git - Git rebase again then push (again) is rejected
- ruby-on-rails - 通过自定义控制器操作将 ActiveStorage 文件发送给用户
- javascript - 为什么一旦我们将相同的函数添加到它的原型中,作为对象属性的函数就无法访问?
- c++ - Why does vc++ compiler cause this statistical pattern?
- javascript - 同位素向 div 添加随机样式
- java - 将控制权传递给超类时的方法绑定
- angular - 我们可以在 Angular 2 中创建多个具有相同名称的组件吗?
- javascript - Webpack 从 .jsx 文件中删除 css?
- c++ - 在 boost 中从 graphviz 读取的问题