React Axios和Fetch POST方法无法使用C#Web API令牌请求

问题描述 投票:1回答:1

我正在努力使用react获得一个C#Web API身份验证令牌。我有一个正确的邮递员请求;它按预期给我我的令牌:

enter image description here

我尝试使用Axios和Fetch重新创建此请求。请求如下:

Attempt 1:
fetch('http://localhost:56765/token', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: JSON.stringify({ username: '[email protected]', password: 'Test123!', grant_type: 'password' })
})

Attempt 2:
axios('http://localhost:56765/token', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: JSON.stringify({ username: '[email protected]', password: 'Test123!', grant_type: 'password' })
})

Attempt 3:
const data = JSON.stringify({ username: '[email protected]', password: 'Test123!', grant_type: 'password' });
const headers = { 'Content-Type': 'application/x-www-form-urlencoded', };
axios.post('http://localhost:56765/token', data, { headers })

当我提出请求时,响应是:

400 Bad Request
{"error":"unsupported_grant_type"}

图片示例:enter image description here

有谁知道我哪里出错了?

编辑:

对我有用的代码是安装qs然后:

var qs = require('qs');

const data = qs.stringify({ username: '[email protected]', password: 'Test123!', grant_type: 'password' });
axios.post('http://localhost:56765/token', data)

我能够完全省略标题。

非常感谢Brub在圣诞节回答!

reactjs asp.net-web-api fetch axios
1个回答
1
投票

您正在传递application-x-www-form-urlencoded的内容类型,但是类型为application / json的实际表单数据。您希望将数据发布为此处描述的form-urlencoded:

https://github.com/axios/axios/issues/350#issuecomment-227270046

注意Oauth 2.0规范要求application / x-www-form-urlencoded

https://tools.ietf.org/html/rfc6749#section-4.3.2

© www.soinside.com 2019 - 2024. All rights reserved.