0

我正在尝试在 NodeJS 中使用 Axios 编写 Post 方法。

我在 post 方法中有以下内容作为参数传递

url = http:/xyz/oauthToken
header 'authorization: Basic kdbvkjhdkhdskhjkjkv='\
header 'cache-control:no-cache'
header 'content-type: application/x-www-form-urlencoded'
data 'grant_type=password&username=user123&password=password123'

正如我尝试使用以下代码但 Axioz 的新手,不确定如何准确地实现带有授权类型的主体响应的标头。

var config = {
 headers: {'Authorization': "bearer " + token}
};

var bodyParameters = {
  data 'grant_type=password&username=user123&password=password123'   
}

Axios.post( 
 'http:/xyz/oauthToken',
 bodyParameters,
 config
).then((response) => {
   console.log(response)
}).catch((error) => {
  console.log(error)
});     

任何帮助/建议将不胜感激:-)

4

1 回答 1

2

目前,axios 不方便使用表单编码的数据;它主要针对 JSON 进行了优化。但是,正如此处记录的那样,这是可能的。

const querystring = require('querystring');

const body = querystring.stringify({ 
  grant_type: 'password',
  username: 'user123',
  password: 'password123'
});

axios.post('http:/xyz/oauthToken', body, { 
  headers: {
    authorization: `bearer ${token}`,
    'content-type': 'application/x-www-form-urlencoded'
  }
});
于 2018-08-06T18:22:27.800 回答