简体   繁体   English

为什么在一种情况下我在ExpressJS中出现cors错误,而在另一种情况下却没有?

[英]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.

相关问题 为什么在使用 cors 进行服务器端 apollo 客户端查询时会收到 500 http 错误? - Why am I getting 500 http error when making serverside apollo client queries with cors? 为什么我会从 Google Cloud Functions 上不变的来源收到间歇性 CORS 错误? - Why am I getting an intermittent CORS error from an unchanging origin on Google Cloud Functions? 为什么会出现此错误? - Why am I getting this error? 我在 Node js 中的 heroku 上收到 CORS 错误 - I am getting CORS error on heroku in Node js 尝试使用 CORS 时出现错误“未定义标头” - I am getting an error "header is not defined" while tring to use CORS 为什么我总是在jquery ajax的情况下得到401(未经授权)错误 - Why i am always getting 401 (Unauthorized) error in case jquery ajax 为什么我的case语句布尔分配中出现非法令牌错误? - Why am I getting an Illegal Token error in my case statement boolean assignment? 为什么我会像模式一样在每个其他数组中获得一个空数组项? (JavaScript) - Why am I getting one empty array item in every other array like a pattern? (JavaScript) 为什么我没有通过ID获得一件物品? - Why am I not getting one item by id? 我收到“next is not a function”的错误。 相同的代码适用于我更喜欢一位先生的其他来源 - I am getting error that "next is not a function" . The same code is working for the other source which i am preferring from one sir
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM