从python移动到node



我多年来一直在使用这个python代码片段:

payload = {'grant_type': "password",
'username': "me@me.com",
'password': "mypassword",
'client_id': "7xxxxxxxx",
'client_secret': "jxxxxxxxx",
'scope': 'read_presence read_thermostat'}
try:
response = requests.post(
"https://api.acme.com/oauth2/token", data=payload)
response.raise_for_status()
print(response.json())
except requests.exceptions.HTTPError as error:
print(error.response.status_code, error.response.text)

现在我需要将相同的代码移动到node/expressjs。我尝试过这个代码,但它总是以";400:错误的请求":

app.get("/get_codes", (req, res) => {
const axios = require('axios');
const options = {
grant: 'password',
username: "me@me.com",
password: "mypassword",
client_id: '7xxxxxxxxxx',
client_secret: 'jxxxxxxxxxxxxx',
scope: 'read_presence read_thermosta'
};
const params = Object.entries(options)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&')
axios.post('https://api.acme.com/oauth2/token', params)
.then(response => {
res.send(response);
})
.catch(error => {
res.send(error);
});
});

如果您必须将数据作为application/x-www-form-urlencoded发送,您应该更喜欢使用URLSearchParams API进行序列化:

const params = new URLSearchParams(options)

如果出于任何原因必须自己序列化它,可以显式地传递内容类型头:

axios({
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: params,
url: 'https://api.acme.com/oauth2/token',
};

当然,正如@qrsngky在评论中指出的那样,看看你的拼写;(

最新更新