gpt4 book ai didi

javascript - sails 错误 : undefined is not a function

转载 作者:搜寻专家 更新时间:2023-10-31 23:46:30 25 4
gpt4 key购买 nike

我正在尝试将 sails 实现为中间服务器,但我无法通过 Sails 服务器进行 api 调用。它在成功的 api 调用时运行良好,但在 Api 调用失败时不起作用。它给出了这个错误。

this.error(res,err);
^

TypeError: undefined is not a function
at error (/Users/nitin.tiwari/owner-app-backend/api/controllers/ApiController.js:26:12)
at IncomingMessage.<anonymous> (/Users/nitin.tiwari/owner-app-backend/api/services/XHR.js:54:11)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickDomainCallback (node.js:381:11)

这是我的 ApiController.js

/**
* ApiController
*
* @description :: Server-side logic for managing apis
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/

var config = sails.config;

module.exports = {

/**
* @ApiController.ready()
*
* Prepare request object and calls XHR.send at the end.
*
*/
ready: function(req, res, method, data){
var options;
var data = data || '';
var protocol = 'http';
var success = function(response){
return res.ok(response);
},
error = function(err){
this.error(res,err);
};
options = {
hostname: config.api.host,
path: req.originalUrl,
method: method,
headers: {
'Content-Type': 'application/json'
}
}

console.log(options,data);
XHR.send(options, data, success, error, protocol);
},

/**
* @ApiController.get()
*
* Serves all the get request.
*
* Makes XHR to Rails API and reverts the response.
*
*/
error:function(res,err){
if(err.status == 422 && err.error.error.code == 41){
var obj = {
id: -1
}
return res.ok(obj);
}
return res.apiError(err);
},

get: function(req, res){
return this.ready(req, res, 'GET');
}

};

我已经实现了错误函数,但它显示为未定义。我现在无法调试它。

最佳答案

这是因为您在 error 回调中使用 this,其中 this 的引用已更改,因此未定义 this.error。为了做到这一点,请将其引用存储在一些变量并使用那个变量而不是这个变量。

var protocol = 'http';
var self = this;
var success = function(response){
return res.ok(response);
},
error = function(err){
self.error(res,err);
};

关于javascript - sails 错误 : undefined is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39547993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com