No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

后端 未结 13 1711
有刺的猬
有刺的猬 2020-11-22 02:27

i\'ve created a small API using Node/Express and trying to pull data using Angularjs but as my html page is running under apache on localhost:8888 and node API is listen on

13条回答
  •  礼貌的吻别
    2020-11-22 03:21

    Try adding the following middleware to your NodeJS/Express app (I have added some comments for your convenience):

    // Add headers
    app.use(function (req, res, next) {
    
        // Website you wish to allow to connect
        res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
    
        // Request methods you wish to allow
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    
        // Request headers you wish to allow
        res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    
        // Set to true if you need the website to include cookies in the requests sent
        // to the API (e.g. in case you use sessions)
        res.setHeader('Access-Control-Allow-Credentials', true);
    
        // Pass to next layer of middleware
        next();
    });
    

    Hope that helps!

提交回复
热议问题