[英]Why am I getting an error with cors in ExpressJS in one case, but not the other?
I'm setting up a database and connecting it to some routes. 我正在建立一个数据库并将其连接到某些路由。 I've managed to get it to work for one route but not the other.
我设法使它在一条路线上起作用,但在另一条路线上却没有。 The 'register' route works but the 'login' route doesn't.
“注册”路由有效,但“登录”路由无效。 When I try to run the login route, I get a 'cors error.'
当我尝试运行登录路由时,出现“ cors错误”。
I've tried to use console.logs to see where the problem lies. 我尝试使用console.logs来查看问题所在。 I also tried adding cors as well to my node server.
我还尝试将cors也添加到我的节点服务器。
const app = express();
app.use(cors());
Here's the backend code for the '/register' route that actually works. 这是实际起作用的“ / register”路由的后端代码。
app.post('/register', (req, res) => {
const { email, password } = req.body;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("expense_tracker");
var myobj = {
email: email,
password: password,
budget: "100",
spent: "0",
expenses: [],
food: "0",
clothing: "0",
personal: "0",
entertainment: "0",
other: "0"
};
dbo.collection("users").insertOne(myobj, function(err, response) {
if (err) throw err;
console.log("1 document inserted");
console.log(response.ops);
if(email !== '' || password !== ''){
res.json(response.ops);
}else{
res.status(400).json("One of the fields is blank; couldn't return user");
}
db.close();
});
});
})
And here is where it is connected to my react app: 这是它连接到我的应用程序的地方:
onSubmitRegister = () => {
console.log(this.state.signinPassword);
fetch('https://server-budget-blaze349.c9users.io/register', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signinEmail,
password: this.state.signinPassword
})
}).then(response => response.json())
.then(user => {
console.log('user', user);
if(user){
this.props.onRouteChange('budget');
this.props.loadUser(user[0]);
}
})
}
I receive a working JSON object when I request. 当我请求时,我会收到一个有效的JSON对象。
However when do something similar for the login: 但是,当对登录执行类似操作时:
app.post('/signin', (req, res) => {
const { email, password } = req.body;
console.log("FRONT END : " + password + ", " + email);
console.log("BACK END: ", database[0].password);
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("expense_tracker");
var query = { email: email, password: password };
dbo.collection("users").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
res.json(result.ops[0]);
db.close();
});
});
})
And the front end: 和前端:
onSubmitSignIn = () => {
console.log(this.state.signinPassword);
fetch('https://server-budget-blaze349.c9users.io/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signinEmail,
password: this.state.signinPassword
})
}).then(response => response.json())
.then(user => {
console.log('user', user);
if(user){
this.props.loadUser(user);
this.props.onRouteChange('budget');
}
})
}
I get this error: 我收到此错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I've been trying to figure out why its happening but I'm still not quite sure. 我一直在试图弄清楚为什么会发生这种情况,但我仍然不太确定。 Any help would be much appreciated on how to fix this 'cors' error.
任何帮助将不胜感激如何解决此“ cors”错误。
Thanks 谢谢
Replace app.use(cors())
with 将
app.use(cors())
替换为
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();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.