【问题标题】:Axios: Send variable in the body of a POST request and not paramsAxios:在 POST 请求的正文中发送变量而不是参数
【发布时间】:2019-07-09 22:50:47
【问题描述】:

我正在做一个项目,我需要在请求正文中发送身份验证变量,而不是作为参数。我看到 POST 请求在文档中将第二个参数作为正文发送,但在 .NET 服务中出现错误。

_response: "{"error":"invalid_clientId","error_description":"ClientId should be sent."}"

当我没有在正文中发送参数时,我在 PHP 中遇到了同样的错误,但值与我在此 POST 请求中使用的值相同,因此我知道参数和值是正确的。

这是我所拥有的:

axios.post(`https://myawesomeapi.com`, 
{username:this.state.email_address, password:this.state.password, grant_type:'password', client_id:'thisAppsClientID'}, 
{headers: { 'content-type':'application/x-www-form-urlencoded', 'accept':'application/json' }}
).then( res => {
  let result = res.data;
  console.log(result);
})
.catch( (e) => {  console.log(e.response); });

当我 console.log 并检查错误响应时,我看到:

config:
   adapter: ƒ xhrAdapter(config)
   data: "{"username":"myusername","password":"mypassword!","grant_type":"password","client_id":"thisAppsClientID"}"
   headers: {Accept: "application/json, text/plain, */*", Content-Type: "application/x-www-form-urlencoded"}
...

如果有帮助,这就是我在 guzzle 中的工作:

    $this->client->request('post', 'https://myawesomeapi.com',
['form_params' => ['username' => $input['username'], 'password' => $input['password'], 'client_id'=>'thisAppsClientID', 'grant_type'=>'password']],
['headers' => ['accept' => 'application/json','Content-Type' => 'application/x-www-form-urlencoded']]);

用户名、密码、grant_type 和 client_id 是否作为正文传递?我搞砸了如何发送标题?谢谢,让我知道!

【问题讨论】:

  • 是的,您正在正确发送参数。你确定“application/x-www-form-urlencoded”内容类型吗?
  • 这是作为参数提供给我的,它似乎在 Postman 和 Guzzle for PHP 中工作。有什么不同的东西对 JS 更好吗?
  • 您是否尝试过以正确的大小写格式编写标题?例如:'Content-Type' 而不是:'content-type'
  • 你也可以尝试将身体串起来。 axios.post(..., JSON.stringify(data), ...)
  • 我为数据添加了 JSON.stringify({username:this.state.email_address, password:this.state.password, grant_type:'password', client_id:'thisAppsClientID'}) 但得到同样的错误...

标签: javascript react-native axios


【解决方案1】:

我知道我在使用 axios 时遇到了类似的问题,但我从未完全弄清楚。但是,我能够收到与Form Data 一起工作的帖子请求。试试下面的 sn-p。我希望它有效。

const dataForm = new FormData();
dataForm.append('username', this.state.email_address);
dataForm.append('password', this.state.password);
dataForm.append('grant_type', 'password');
dataForm.append('client_id', 'thisAppsClientID');

axios.post('https://myawesomeapi.com', dataForm)
.then(res => {
  let result = res.data;
  console.log(result);
})
.catch(e => { 
  console.log(e.response); 
});

【讨论】:

  • 感谢 sn-p。它仍然抛出相同的 clientID 需要提供错误。 ://
  • 解决方案是使用 qs 库对数据进行编码:github.com/ljharb/qs 按照:github.com/axios/…
  • 谢谢,在我的情况下,后端不期望用户名密码在帖子正文中为 json。添加作为表单参数发送的 FormData 并修复了问题。
猜你喜欢
  • 2019-02-02
  • 2021-03-16
  • 2018-04-13
  • 2021-01-03
  • 2018-09-04
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 2013-09-03
相关资源
最近更新 更多