将请求从python转换为节点js

2024-10-03 02:40:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python请求,它在我尝试使用的API上工作。 我尝试在Node js中转换它,但是我无法执行请求

python请求:

import requests
url = 'https://simplivity@xxxx/api/'

hms_username = 'xxxx'
hms_password = 'xxxx'

response = requests.post(url+'oauth/token', auth=('simplivity', ''), verify=False, data={
  'grant_type':'password',
  'username':hms_username,
  'password':hms_password})
print(response.json())

节点JS请求:

var https = require("https");

var options = {
    host: "simplivity@xxxx",
    path: "/api/oauth/token",
    method: "POST",
    headers: {
        "Content-Type": "application/json",
    }
};

var req = https.request(options, function (res) {
    res.on("data", function (data) {
        console.log(data);
    });
    res.on("end", function () {
        console.log(data);
    });
});

const data = JSON.stringify({
    grant_type: 'password',
    'username': 'xxxx',
    'password': 'xxxx'
})

req.write(data);
req.end();

我不明白我在他们之间做错了什么

我没有在节点js中传递auth='simplivity',因为我不知道把它放在哪里

以下是输出:

Python:

tWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
{'access_token': 'xxxx', 'token_type': 'bearer', 'expires_in': 86399, 'scope': 'read write', 'updated_at': 1560771243707}

节点js:

events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: getaddrinfo EAI_FAIL simplivity@xxx simplivity@xxx:443
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
Emitted 'error' event at:
    at TLSSocket.socketErrorListener (_http_client.js:392:9)
    at TLSSocket.emit (events.js:189:13)
    at emitErrorNT (internal/streams/destroy.js:82:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)
[nodemon] app crashed - waiting for file changes before starting...

谢谢


Tags: httpstokendata节点vartypejsusername