【问题标题】:React Js Axios Post Request not receiving body back from web apiReact Js Axios 发布请求未从 web api 接收到正文
【发布时间】:2017-08-18 21:02:56
【问题描述】:

所以我有一个 web api,它被设置为生成一个令牌,以便在您向其发送相同的用户名和密码时返回,如果您提供这样的正文,这将通过邮递员工作

这可行,它为您提供了一个令牌和正确的信息,但是当我从 chrome、firefox 或 ie 执行此操作时,它给了我一个错误,我的代码是这样的,

var d = {
        username: Uname,
        surname: Pword,
        grant_type: "password",
        client_id: "099153c2625149bc8ecb3e85e03f0022",
    };
    console.log(d);

    var self = this;
    return (
        axios.post('http://localhost/hydraauth/oauth/token', {
            headers: {
                'Content-Type': 'application/json',
            },
            data: d
        }).then(function (response) {
            console.log(response.data)
            self.setState({
                isLoggedIn: true,
                Uname: Uname,
            }, function () {
                sessionStorage.setItem("Login", true);
                sessionStorage.setItem("Uname", Uname)
                window.location.href = "/";
            });
        }).catch(function (error) {
            if (error.response){
            console.log(error.response)
            console.log(error.response.data);
            console.log(error.response.status);
            console.log(error.response.headers);
            } else {
            window.alert("Incorrect Username Or Password Or Unauthorized To Access This.")
            }
        })
    );

这给了我 chrome 中的这个错误

这里是错误扩展

chrome中网络标签的图像,响应标签为空

【问题讨论】:

  • 我猜这个问题是因为CORS
  • @BardiaRastin 从邮递员那里工作时怎么可能是cors
  • 因为CORS只存在于浏览器中...
  • cors 错误在哪里,因为在我的 web api 中它是用 cors 设置的
  • 看看开发者工具中的网络标签,也看看thisthis

标签: javascript reactjs axios


【解决方案1】:

Axios 通过 body 发送数据有问题,所以你需要使用npm plugin query string

并像这样使用它

axios.post("http://localhost/hydraauth/oauth/token", querystring.stringify({ "username": Uname, "password": Pword, "grant_type": "password", "client_id": "eyJjbGllbnRfaWQiOiJTYXZ2eS1Dcm0tUmVhY3QtSnMtU3lzdGVtIn0" }))

【讨论】:

    猜你喜欢
    • 2021-11-02
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 2019-07-05
    • 1970-01-01
    • 2022-06-22
    相关资源
    最近更新 更多