node.js - 与 Mojang 身份验证服务器交互的问题
问题描述
我正在尝试从 Mojang 身份验证 API 获取客户端令牌,可以在此处找到https://wiki.vg/Authentication。但是,每当我尝试发出请求时,都会收到以下响应:
{error: 'ForbiddenOperationException', errorMessage: 'Forbidden'}
API 表明这是因为我的凭据无效,但我收到的 errorMessage 与他们的任何示例都不匹配。我尝试通过 python 的 Requests 模块执行相同的请求,并且效果很好,这让我相信我没有正确发送我的 https 请求。我知道我可能忽略了一些非常基本的东西,但是如果有人告诉我我做错了什么,我将不胜感激。这是我的代码:
有效的 Python 代码:
import requests
url = 'https://authserver.mojang.com/authenticate'
data = {"username":"--username--", "password":"--password--"}
res = requests.post(url, json=data)
print(res.json())
不起作用的 Javascript 代码:
var https = require('https');
var options = {
host: 'authserver.mojang.com',
path: '/authenticate',
method: 'POST',
headers: {"username":"--username--","password":"--password--"}
}
https.request(options, (res)=>{
var body = ''
res.on('data', (d)=>{
body+=d;
});
res.on('end', ()=>{
resp = JSON.parse(body);
console.log(resp);
});
}).end();
解决方案
问题是您将凭据直接作为 HTTP 标头而不是作为 POST 数据发送。试试这个:
var https = require('https');
var data = JSON.stringify({"username":"--username--","password":"--password--"})
var options = {
host: 'authserver.mojang.com',
path: '/authenticate',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
var req = https.request(options, (res)=>{
var body = ''
res.on('data', (d)=>{
body+=d;
});
res.on('end', ()=>{
resp = JSON.parse(body);
console.log(resp);
});
});
req.write(data);
req.end();
推荐阅读
- reactjs - 如何在 styled-components 中扩展多个组件的样式
- apache-nifi - 如何通过引用 nifi 中传入流文件中的表和行 ID 来动态获取行
- r - 绘制直线的结果看起来不直
- angular - 结合角度和grails
- prolog - 在 Prolog 中插入剪切以使关系子句绑定但双向
- python - 如何过滤 url 中使用等于或大于条件的数据?
- dijit.form - 在 dijit.form.select 它没有选择合适的
- php - 如果 mySQL 行的 innerHTML X 则将其移动到表的顶部
- bash - 如何在 bash 脚本中使用命令读取文件中的多行并选择一个数字来定义变量
- python - dask 数据帧 head() 返回空 df