Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have problem with my node.js API. I have API running on port 3000, and angular frontend with port 4200.

When i send request from angular to API, i have error with CORS. I tried three different solution, but still not working.

  1. First solution is install cors package, and add to code

app.use(cors());

  1. Second solution is add code below:
 app.use((req, res, next) => {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
   next();
})
  1. Last solution is add code below, with frontend url:
app.use(cors({
  origin: 'http://frontend.com:4200'
}));

None of the above worked, i.e. I still get an error with CORS all the time. When i send request from Postman, all works fine.

My actual code:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const carRoutes = require('./routes/car');
const sequelize = require('./util/db');
const cors = require('cors');

sequelize.sync().catch(error => {
  console.log(error);
});

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

app.use(carRoutes);
app.listen(3001);

Error message:

A request to a resource of another origin has been blocked: the "Same Origin Policy" policy does not allow remote resources to be loaded from "http://localhost:3000/car" (failed CORS request).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
317 views
Welcome To Ask or Share your Answers For Others

1 Answer

Sometimes CORS is more than just Access-Control-Allow-Origin. Try the following:

// Set up CORS
app.use(cors({
    origin: true, // "true" will copy the domain of the request back
                  // to the reply. If you need more control than this
                  // use a function.

    credentials: true, // This MUST be "true" if your endpoint is
                       // authenticated via either a session cookie
                       // or Authorization header. Otherwise the
                       // browser will block the response.

    methods: 'POST,GET,PUT,OPTIONS,DELETE' // Make sure you're not blocking
                                           // pre-flight OPTIONS requests
}));

You may also play around with allowedHeaders, exposedHeaders etc. Setting maxAge will reduce the number of pre-flight requests - it doesn't really fix cors issues but will reduce network traffic.

Note on origin: true. If your endpoint requires credentials then the browser will not respect the * pattern. The Access-Control-Allow-Origin header must match the url of the request (including weather it's http or https). Fortunately the cors middleware will do this automatically for you if you set origin to true


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...