【问题标题】:Why am I getting an error with cors in ExpressJS in one case, but not the other?为什么在一种情况下我在 ExpressJS 中遇到 cors 错误,而在另一种情况下却没有?
【发布时间】:2019-11-02 19:48:10
【问题描述】:

我正在建立一个数据库并将其连接到一些路由。我设法让它适用于一条路线,但不适用于另一条路线。 “注册”路线有效,但“登录”路线无效。当我尝试运行登录路由时,出现“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();
  });
});
})

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

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.

我一直在试图弄清楚为什么会发生这种情况,但我仍然不太确定。任何有关如何解决此“cors”错误的帮助将不胜感激。

谢谢

【问题讨论】:

标签: javascript node.js reactjs mongodb express


【解决方案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();
});

【讨论】:

    猜你喜欢
    • 2013-12-28
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2022-12-18
    相关资源
    最近更新 更多