用于使用Axios在ReactJS中进行注册的简单令牌-Rails API

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

我正在创建一个与ReactJS通信的简单Rails API。我已经使用Postman测试了API端点,它们可以正常工作。

但是,当我提交自己的ReactJS表单以注册新用户时,我遇到了一些问题。我收到错误:

POSThttp://www.localhost:3000/api/v1/registration/reg401(未授权)

我认为问题是在我的发帖请求期间未提交或创建身份验证令牌。

ReactJS发布请求

这是处理表单的提交按钮的ReactJS。

function handleFormSubmit(e) {
    e.preventDefault()
    axios.post("http://www.localhost:3000/api/v1/registration/reg")
        .then(res => {console.log(res)})
        .catch(err=>{console.log(err)})

}

如果尝试使用Postman或在Rails Console中,则可以创建一个新用户。例如,在邮递员中,我只是这样做:1)开机自检localhost:3000/api/v1/registration/reg2)创建一个随机用户:3)

{
    "email": "[email protected]",
    "password": "12345678"
}

4)我回来了:

{
    "id": 4,
    "email": "[email protected]",
    "created_at": "2019-12-28T22:59:59.454Z",
    "updated_at": "2019-12-28T22:59:59.454Z",
    "authentication_token": "SzqjkJd5ocbVh1MziZZA"
}

ReactJS不会发生这种情况,我回来了:

POSThttp://www.localhost:3000/api/v1/registration/reg401(未授权)

ruby-on-rails reactjs
1个回答
0
投票

您需要附加数据和授权令牌。

var user= {
   key: "value"
}

var config = {
    headers: {'Authorization': "bearer " + token}
};

axios.post('http://www.localhost:3000/api/v1/registration/reg/user', 
  user,
  config
    )
    .then(function (response) {
     console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });

如果您使用的是Http基本身份验证,只需添加

auth: {
    username: '....',
    password: '...'
} 

插入配置。

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