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

时间:2019-06-20 02:58:08

标签: javascript node.js reactjs mongodb express

我正在建立一个数据库并将其连接到某些路由。我设法使它在一条路线上起作用,但在另一条路线上却没有。 “注册”路由有效,但“登录”路由无效。当我尝试运行登录路由时,出现“ cors错误”。

我尝试使用console.logs来查看问题所在。我还尝试将cors也添加到我的节点服务器中。

    const app = express();
    app.use(cors());

这是实际上有效的'/ 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();
  });
});
})

这是它连接到我的React应用程序的地方:

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]);
        }
    })
   }  

我在请求时收到一个有效的JSON对象。

但是何时对登录进行类似的操作:

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();
  });
});



})

前端:

   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');
        }
    })
  }  

我收到此错误:

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.

我一直在试图弄清楚为什么会发生这种情况,但我仍然不太确定。对于如何解决此“错误”错误,我们将提供任何帮助。

谢谢

1 个答案:

答案 0 :(得分:1)

代替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();
});