我正在创建一个与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/reg
2)创建一个随机用户: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(未授权)
您需要附加数据和授权令牌。
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: '...'
}
插入配置。