【发布时间】:2018-04-25 14:20:48
【问题描述】:
我在使用 Request npm 时的回调有一些问题。 我的项目是 Sailsjs 为用户开发的 API,另一方面我使用 reactjs 作为前端,我使用 Request npm 与 API 进行通信。 我的回调有一些问题。
我的代码:
handleClick(event) {
var apiBaseUrl = "http://localhost:1337/user";
if (
this.state.first_name.length > 0 &&
this.state.last_name.length > 0 &&
this.state.email.length > 0 &&
this.state.password.length > 0
) {
request.post({url : apiBaseUrl + "/store", form :{
first_name: this.state.first_name,
last_name: this.state.last_name,
email: this.state.email,
password: this.state.password
}}, function(response) {
console.log(response);
if (response.data.code === 200) {
var loginscreen = [];
loginscreen.push(
<Login
parentContext={this}
appContext={this.props.appContext}
key = {rand}
/>
);
var loginmessage = "Not Registered yet.Go to registration";
this.props.parentContext.setState({
loginscreen: loginscreen,
loginmessage: loginmessage,
buttonLabel: "Register",
isLogin: true
});
} else {
console.log("some error ocurred", response.data.code);
}
});
} else {
alert("Input field value is missing");
}
}
post 请求运行良好,当我检查数据库时,我发现用户已保存,chrome 中网络 onglet 的响应很好,但是当我执行 console.log(response) 时,它总是 null。不知道是不是我的回调不对,还是别的原因。
后端
// Store user
store: function(req, res) {
var params = _.extend(req.query || {}, req.params || {}, req.body || {});
console.log(params);
UserService.store(params, function(err, user) {
if (err) return res.json();
if (!user) return res.json();
return res.send({
"code": 200,
"success": "user registered sucessfully"
});
});
},
你能帮我解决这个问题吗?
【问题讨论】:
-
您能在服务器端显示 POST 处理程序的代码吗?
-
ok 就是这样 : // 存储用户存储:function(req, res) { var params = _.extend(req.query || {}, req.params || {}, req.正文 || {});控制台.log(参数); UserService.store(params, function(err, user) { if (err) return res.json(); if (!user) return res.json(); return res.send({ "code": 200, "success ": "用户注册成功" }); }); },
-
请将代码添加到您的问题中,编辑帖子并包含它以提高可读性。
-
好的完成 ...
-
将第一个
res.json()替换为res.serverError(),将第二个替换为res.notFound(),我认为res.send({...});永远不会被执行,这次你会得到500或404错误,请尝试查看。
标签: reactjs npm callback request sails.js