1

我正在尝试通过 API 在 localhost 上登录我的 Rocket.chat 应用程序。
当我向http://localhost:3000/api/login发送带有数据的 POST 时:{"user":"myusername","password":"mypassword"}
无论使用 xhr 请求、axios 还是 jquery ajax,我都会收到带有状态错误的响应 401。

但是当我使用 python virtualenv 或 curl 发送相同的数据时,响应为 200 并且状态成功。
我究竟做错了什么?为什么使用 javascript 发送时 POST 失败,使用 python 或 curl 发送时通过?

var xhr = new XMLHttpRequest();
  xhr.open("POST", 'http://localhost:3000/api/login/', true);
  xhr.send(JSON.stringify({
  user: "myusername",
  password: "mypassword"
}));
// result: {status: "error", message: "Unauthorized"}

我正在发送没有标头的登录请求,因为:

xhr.setRequestHeader('Content-Type', 'application/json');

返回 500

以下是来自 Chrome 的请求详细信息:
在此处输入图像描述

4

2 回答 2

5

您正在与您发出 ajax 请求的域不同的域上运行火箭聊天。您发出 ajax 请求的域和端口应与目标 url 的域和端口相同。这是因为 Web 浏览器中称为跨源资源共享 (CORS) 的安全功能。请参阅https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

要修复此错误,您的 Web 服务器需要允许来自其他域的请求。

于 2016-10-27T10:25:19.493 回答
-1

试试这个代码

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST","http://localhost:3000/api/login/");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF- 8");xmlhttp.send(JSON.stringify({name:"myusername", time:"mypassword"}));
于 2016-10-27T08:12:45.727 回答