gpt4 book ai didi

javascript - 使用 Node js Express 登录帖子事件抛出 401 错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:35 24 4
gpt4 key购买 nike

我尝试通过不同的域登录,而我的服务器位于另一个域上。我的loginmodule.js从下面的HTML页面收集用户名和密码是代码。我还允许在代码中使用cors。

var name=$('#username').val();
var pass=$('#password').val();
var surl = "http://192.165.2.33:3000/users/login/";
console.log('link');
$.ajax({
type: 'POST',
url: surl,
crossDomain: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ username:'name', password:'pass'}),
dataType: "json",
async: true,
cache: false,
success: function(responseText,status){
if(status=='true') console.log('success');

}
});

这给了我一个 401 未经授权的错误。我的 server.js 文件中应该包含哪些内容以避免出现同样的情况。我的 Server.js 文件具有以下代码。

var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};

然后我把它放在顶部

app.use(allowCrossDomain);

最佳答案

您要发送此内容(不是变量,而是字符串):

...
data: JSON.stringify({ username:'name', password:'pass'}),
...

但是您可能想发送该内容(html 输入的实际内容):

...
data: JSON.stringify({ username:name, password:pass}),
...

所以删除撇号,它应该可以正常工作!

关于javascript - 使用 Node js Express 登录帖子事件抛出 401 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44046737/

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