React Axios 和 Fetch POST 方法不适用于 C# WebAPI 令牌请求

React Axios and Fetch POST method not working with C# WebAPI token request

我正在努力使用 React 获取 C# WebAPI 身份验证令牌。我有一个可以正常工作的 Postman 请求;它按预期给了我令牌:

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

Attempt 1:
fetch('http://localhost:56765/token', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: JSON.stringify({ username: 'test@test.com', 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: 'test@test.com', password: 'Test123!', grant_type: 'password' })
})

Attempt 3:
const data = JSON.stringify({ username: 'test@test.com', 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"}

图片示例:

有人知道我哪里错了吗?

编辑:

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

var qs = require('qs');

const data = qs.stringify({ username: 'test@test.com', password: 'Test123!', grant_type: 'password' });
axios.post('http://localhost:56765/token', data)

我能够完全省略 header。

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

您传递的是 application/x-www-form-urlencoded 的内容类型,但传递的是 application/json 类型的实际表单数据。您想要 post 此处描述的 form-urlencoded 数据:

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

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

https://www.rfc-editor.org/rfc/rfc6749#section-4.3.2