express - 我们如何从 react native 的 fetch 函数中获取 post 数据来表达 api?
问题描述
问题:
我们如何从 react native 中的 fetch 函数中获取 post 数据以表达 api?
面临的问题:
我尝试了以下过程,但没有在后端 API 中获得这些变量。
如何在后端 API 中实现变量?任何建议都受到高度赞赏。
这是反应式本机获取功能:
反应本机获取功能:
login = async () => {
await fetch('http://192.168.1.160:8001/api/login', {
method: 'POST',
mode: 'cors',
cache: 'default',
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
.then ((response) => response.json())
.then ((res) => {//console.log(res);
if(res.error === false){
AsyncStorage.setItem('user', res.data);
this.props.navigation.navigate('profile');
} else{
// alert(res.message);
}
})
}
Express-API:
快递API如下:
module.exports = function (req, res) {
console.log('TEST',req.body);
let { email, password } = req.body;
let input = { email, password };
const validator = loginValidator(input);
if (validator.error) {
return res.status(400).json({
error: true,
message: validator.error.details,
});
} else {
models.users.findOne({
where: { email: email }
}).then(user => {
if (!user) {
return res.status(400).json({
error: true,
message: {
key: 'email',
text: MessageHelper.email_already_exist
}
});
} else if (!bcrypt.compareSync(password, user.password)) {
return res.status(400).json({
error: true,
message: {
key: 'password',
text: MessageHelper.password_not_valid
}
});
} else {
var token = jwt.sign({ userid: user.id },Config.get('jwt.privatekey'));
models.users.update({ token: token },{ where: { id: user.id } }).then(function(result){
return res.json({
error: false,
message: MessageHelper.user_token_updated,
token: token,
data: {
user_id: user.id,
firstname: user.firstname,
lastname: user.lastname,
username:user.username,
email: user.email,
mobile: user.mobile,
token: user.token
}
});
}).catch(function(error){
return res.status(400).json({
error: true,
message: error
});
})
}
});
}
}
解决方案
Fetch 还接受一个可选的第二个参数,允许您自定义 HTTP 请求。您可能想要指定其他标头,或发出 POST 请求:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
联网本质上是一种异步操作。Fetch 方法将返回一个 Promise,这使得编写以异步方式工作的代码变得简单:
function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
推荐阅读
- ruby-on-rails - 如何重用net:http session +Ruby on rails
- javascript - 需要 bignumber.js 时出现 Javascript 错误:未捕获的 ReferenceError:未定义要求
- javascript - 唯一名称的异步验证器
- python - Python同质到非同质绘图线
- android - 同时更改工厂对齐和菜单时底部应用栏的闪烁效果
- javascript - 如果用 var 重新声明将对已存在的变量产生影响
- spring-boot - 尝试仅为方法和 PUT 和 DELETE 添加安全性
- angular - 将数据传递给子组件但在 onChanges 后未定义
- c# - 如何在 Visual Studio 2019 的 Windows 窗体应用程序中打印变量?
- android - 无法解析 RecyclerView 中的视图持有者