【问题标题】:Callback not working in request npm回调在请求 npm 中不起作用
【发布时间】:2018-04-25 14:20:48
【问题描述】:

我在使用 Request npm 时的回调有一些问题。 我的项目是 Sailsjs 为用户开发的 API,另一方面我使用 reactjs 作为前端,我使用 Request npm 与 A​​PI 进行通信。 我的回调有一些问题。

我的代码:

 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。不知道是不是我的回调不对,还是别的原因。

form

http response

variables in response

Error

后端

// 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({...});永远不会被执行,这次你会得到500404错误,请尝试查看。

标签: reactjs npm callback request sails.js


【解决方案1】:

其实问题出在你的回调上,回调有两个参数,应该是这样的:

function(error, response) {.....}

error 是第一个参数,响应是第二个参数,你得到null 因为有 no 错误!并且响应被视为错误对象。

【讨论】:

    猜你喜欢
    • 2017-09-11
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多