【发布时间】:2018-05-19 10:12:06
【问题描述】:
我在这里遇到了一个问题,我正在使用 ReactJS 开发一个 Rest API 和一个 Web 应用程序。我正在尝试向 Rest API 发出 fetch 请求,但总是收到一个 401 代码,表示未经授权的访问。我在以下代码中发送fetch request:
SubmitClick(){
if (this.state.password !== this.state.reTypepassword){
alert('Passwords do not match. Please check your data !');
} else {
//console.log(this.state); //debug only
fetch('http://localhost:4000/users/', {
method: 'POST',
headers: {
'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.email,
first_name: this.state.first_name,
last_name: this.state.last_name,
personal_phone: this.state.personal_phone,
password: this.state.password
})
}).then(this.props.history.push('/get')); //change page layout and URL
}
}
如您所见,我在请求中按照以下结构插入了 Authorization 标头:('Authorization' : 'Basic ' + encoding)。我从 Postman 软件的请求中获得了编码值。
这是我的 Rest API 的代码,我在其中配置了允许的用户和密码:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var basicAuth = require('express-basic-auth')
const app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
mongoose.connect('mongodb://localhost/usersregs', { useMongoClient: true });
mongoose.Promise = global.Promise;
app.use(basicAuth({
users: {
'admin': 'supersecret',
'adam': 'password1234',
'eve': 'asdfghjkl'
}
}))
app.use(bodyParser.json());
app.use(function(err, req, res, next){
console.log(err);
//res.status(450).send({err: err.message})
});
app.use(require('./routes/api'));
app.listen(4000, function(){
console.log('Now listening for request at port 4000');
});
使用谷歌浏览器开发者工具,我可以看到这个操作中的请求头,as you can see here
如果我删除了配置用户和密码的部分代码(在 Rest API 中),以及配置授权标头(Web 应用程序)的部分,则代码可以正常工作。我无法使其与 Authorization 标头一起使用。
我应该如何处理 fetch 请求中的 Authorization 标头,以便我可以访问 Rest API?
【问题讨论】:
-
而不是
fetch使用axiosgithub.com/axios/axios -
我试过了,但我仍然收到同样的错误
标签: reactjs http-headers authorization fetch