【问题标题】:Node js express\ react js cors issueNode js express\ react js cors问题
【发布时间】:2020-11-12 13:21:38
【问题描述】:

我正在处理 express js 中的 CORS 问题,所以问题是当我使用 CORS 库时,我在邮递员中通常会收到 cors 标头而没有问题,如下图所示postman response headers

但是当我从我的 React js 调用相同的 api 时,我得到一个 cors 错误,并且响应标头中没有 cors 标头。

第二个问题是当我在我的主应用程序中使用 cors 库时:

code of server.js using CORS in App

我的整个快递服务器很长一段时间都没有返回任何东西。

这里是express js中的相关代码:

//server.js

  const express = require("express");
const bodyParser = require('body-parser');


const app = express();



app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

const dbConfig = require('./config/database.config.js');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

mongoose.connect(dbConfig.url, {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(()=>{
    console.log("Successfully connected to the database");
    
}).catch(err => {
    console.log('Could not connect to the database. Exiting now ...',err);
    process.exit();
    
})

app.get('/',(req, res) => {
res.json({"message" : "Welcome to EasyNotes application. Take notes quickly. Organize and keep track of all your notes."});
});

require('./app/routes/note.routes.js')(app);

app.listen(3000,() => {

    console.log("Server is listening on port 3000");
    
})

这是我的路由js文件

//routing

const cors = require('cors');
module.exports = (app) => {

    const notes = require('../controllers/note.controller.js');

    app.post('/notes', cors(), notes.create);

    app.get('/notes', cors(), notes.findAll);

    app.get('/notes/:noteId', cors(), notes.findOne);

    app.post('/notes/:noteId', cors(), notes.update);

    app.delete('/notes/:noteId', cors(), notes.delete);


}

最奇怪的是,我使用的是相同的 api,但使用了不同的路由,并且它在浏览器中运行良好,就像我使用这条路由时一样:

 app.get('/notes', cors(), notes.findAll);

效果很好。

请帮忙!!

【问题讨论】:

    标签: reactjs express cors


    【解决方案1】:

    通过阅读您的帖子,我不确定您是否完全理解什么是 CORS 以及触发问题的原因。我建议你看看Mozilla explanation

    为了进一步解释,浏览器可能会向您的 API 发出OPTIONS 请求,以检查是否允许跨源请求。为此,您需要使用cors 包,就像您在附加的第二个屏幕截图中显示的那样。 您提到执行此操作时您的应用程序无法运行,这可能是您应该调查的错误,可能在 the github issues of the package 中。

    最后,我从来没有使用过cors(),因为你在路由文件中使用它,只包括屏幕截图中的中间件就足够了,也许这是你提到的第二个问题的原因?

    祝你好运?

    【讨论】:

      【解决方案2】:

      在您的server.js 文件中,您正在使用app.use(cors),但它应该是app.use(cors())。这是我目前正在从事的一个项目中的一个示例

      
      require('./db')
      
      const express = require('express')
      const cors = require('cors')
      const bodyParser = require('body-parser')
      
      const mongoose = require('mongoose')
      
      const postRouter = require('./routes/post')
      
      const app = express()
      
      app.use(cors())
      app.use(bodyParser.json())
      app.use(bodyParser.urlencoded({extended: true}))
      
      app.use('/api', postRouter)
      
      /*
      mongoose.connection.on('connected', () => {
          
          mongoose.connection.db.listCollections().toArray(function (err, names) {
              console.log(names);
          });
      })
      */
      app.post('/', function(req, res) {
          res.sendStatus(200)
      })
      
      
      app.listen(5000, () => console.log("Server started on port 5000"));
      

      【讨论】:

        猜你喜欢
        • 2013-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 2019-03-14
        相关资源
        最近更新 更多