【发布时间】:2020-01-24 03:10:23
【问题描述】:
按照这一系列教程first part here 和second part here 的建议,我使用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',
},
还是没有运气..
【问题讨论】:
-
看起来服务器无法解析正文参数。你能把服务器代码贴在你阅读名字和姓氏的地方吗
-
@nithin 我有 5 个服务器文件:server.js、routes.js、controller.js、res.js、conn.js。这是来自 controller.js 的 sn-p:
exports.createUsers = function(req, res) { var first_name = req.body.first_name; var last_name = req.body.last_name; connection.query('INSERT INTO person (first_name, last_name) values (?,?)', [ first_name, last_name ], function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok("Berhasil menambahkan user!", res) } }); }; -
@nithin 完整的源代码可以在我原来的问题中的教程链接中找到(抱歉是印尼语)
-
我相信,访问req.body需要添加body-parser中间件来表达
-
@nithin 你能发布语法吗?或者也许是一个样本的答案,好吗?
标签: javascript mysql react-native express fetch-api