我正在开发一个项目,我需要在请求正文中发送身份验证变量而不是作为参数。我看到 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 是否作为正文传递?我是否弄乱了如何发送 header ?谢谢并告诉我!
最佳答案
我知道我在 axios 上也遇到过类似的问题,但我一直没有完全弄清楚。但是,我能够获得与 Form Data 一起使用的发布请求。 。尝试下面的代码片段。我希望它能起作用。
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);
});
关于javascript - Axios:在 POST 请求正文中发送变量而不是参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54715341/