【问题标题】:React Axios and Fetch POST method not working with C# WebAPI token requestReact Axios 和 Fetch POST 方法不适用于 C# WebAPI 令牌请求
【发布时间】:2018-06-06 14:51:45
【问题描述】:

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

我已尝试使用 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)

我能够完全省略标题。

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

【问题讨论】:

  • 你试过在服务器端调试这个吗?

标签: reactjs asp.net-web-api fetch axios


【解决方案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://www.rfc-editor.org/rfc/rfc6749#section-4.3.2

【讨论】:

    猜你喜欢
    • 2018-06-22
    • 2018-10-01
    • 2021-08-07
    • 2021-03-24
    • 2019-10-20
    • 2020-07-28
    • 2018-06-07
    • 2020-09-18
    • 2019-08-28
    相关资源
    最近更新 更多