Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

2.3K
Visualizações
Angular client enable CORS

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..... enter image description here

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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());

over 4 years ago · Santiago Trujillo Relatório

0

A little intro:

Cross-Origin Resource Sharing aka CORS is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin (e.g. http://localhost:3000), access to selected resources from a different origin (e.g. http://localhost:8080). In other words, a web app executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own. For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts.

The Access-Control-Allow-Origin header determines which origins are allowed to access server resources over CORS.


How to Fix CORS Issues?

You can do it yourself by creating an Express middleware. Here's the appropriate code snippet:

// Enable CORS for specific origins:


app.use((req, res, next) => {
  // Allow multiple predefined origins
  const allowedOrigins = ["https://deployed-app.com", "http://localhost:3000"];
  const origin = req.headers.origin; // extract the origin from the header
  if (allowedOrigins.indexOf(origin) > -1) { // if the origin is present in our array   
    res.setHeader("Access-Control-Allow-Origin", origin); // set the CORS header on the response
  }
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next(); // move on to the next middleware
});

Alternatively, you can accept all requests, but this option is only appropriate if you're in development or if your API is public :)

 app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    next();
 });

Additionally, there's an Express CORS middleware and this is how you would use it:

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}`);
       });

Important gotcha: When it comes to Express middleware, the order is very important. So make sure CORS is enabled before any other controller/ route/ middleware which may depend on it.

over 4 years ago · Santiago Trujillo Relatório

0

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

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda