Angular client enable CORS

巧了我就是萌 提交于 2019-12-25 03:22:34

问题


CORS is fine on server and works as intended. I tried sending requests to my server's REST API with the angular HTTPClient and I receive a CORS error. Why is this an error if CORS is enabled on the server? Shouldn't it be fine on the client?

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api/blah/blah (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

How can I enable CORS on this request please.....


回答1:


You dont need to enable cors in angular, this is a server side issue. See:

https://stackoverflow.com/a/29548846/4461537




回答2:


For future refrence it was "Davids" answer that assisted me, the cors was not added before all routing.

"..... Meaning, before the route is defined." so right after ... var app = express();

I just use... app.use(cors());




回答3:


There's an Express CORS middleware :

npm install cors --save

Enable All CORS Requests:

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
});

const port = process.env.PORT || 8080;

app.listen(port, () => {
 console.log(`CORS-enabled server is up on ${port}`);

});

Enable CORS for a Single Route

const express = require('express');
const cors = require('cors');
const app = express();

    app.get('/products/:id', cors(), (req, res, next) => {
      res.json({msg: 'This is CORS-enabled for a Single Route'})
    });

     const port = process.env.PORT || 8080;

       app.listen(port, () => {
         console.log(`CORS-enabled server is up on ${port}`);
       });


来源:https://stackoverflow.com/questions/51640206/angular-client-enable-cors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!