【发布时间】: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