我正在尝试制作一个npm模块,用户需要在其中发送其令牌和ID才能进行连接。
这是模块代码:
var https = require('https');
var fetch = require('node-fetch')
module.exports = class Cloud_client {
constructor(client,token){
this.token = token ;
this.client = client;
if(!token) return console.error(`[cdl.js] No token provided`);
if(!client) return console.error(`[cdl.js] No Client Id provided`);
}
login() {
fetch(`https://www.cloudlist.xyz/isvalid/${this.token}`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body:JSON.stringify({client:this.client}),
}).then(async response => {
console.log(response)
return console.error(`[cdl.js] ${response.statusText}`); // eslint-disable-line no-console
})
}
}
服务器端发布处理程序:
app.post("/isvalid/:token", limiter ,async (req, res) => {
if(!req.body.client) return res.status(204).send({message: 'No id provided'});
if(!req.params.token ) return res.status(204).send({message: 'No token provided'});
database.ref(`Bots/${req.body.client}`).once("value",function(data) {
if(data.val() === null) return res.status(204).send({message: 'Invalid user'});
if(!data.val().apiKey) return res.status(204).send({message: "This Client doesn't have an api key yet"});
if(data.val().apiKey === req.params.token) {
res.status(200 ).send({message: `Logged in as ${data.val().bot_name}`});
}else {
return res.status(401).send({message:"Incorrect authorization token."});
}
})
})
我确实收到一条错误消息https://prnt.sc/r8iejl 但是此消息来自代码,在本例中为401,而不是自定义消息“ Inauthorization token不正确”。
当我尝试提供response.body.message或response.message时,我不确定,我无法收到错误代码。我已经尝试过return res.status(401).json({message: "Incorrect authorization token"})
但是我又收到状态错误代码
答案 0 :(得分:2)
我遇到了同样的问题。如果我发送了res.status(401).json({message: "Incorrect authorization token"})
,我会回来的You do not have permission to view this directory or page
。
我的问题是我正在使用iisnode通过IIS运行nodejs。
默认情况下,IIS将替换您发送的所有错误消息。通过在<system.webServer>
(source)下的web.config文件中添加以下代码,可以关闭此行为:
<httpErrors existingResponse="PassThrough" />
重新启动服务器后,我可以取回{message: "Incorrect authorization token"}
。
答案 1 :(得分:0)
问题在于,如果 Express 中有错误,您必须使用正确的键命名约定。
您必须使用 errorMessage
否则 没有 将出现在错误响应中(尽管如果您不使用 errorMessage,您仍然可能会在网络响应中找到一些东西——这让我认为 Express 坏了)。
res.status(401).send({errorMessage: "This is my custom message"})
或
res.status(401).send({errorMessage: {message: "This is my custom object", value: 32}})
希望这有帮助:P