0

I have an Angular7 frontend, and I am trying to send a get request from my Node server. However the Node server is unable to receive the api request itself.

I tried both on node's app.js code: 1>

const cors = require('cors');
app.use(cors());

2>

app.use((req,res,next)=>{
res.header('Access-Control-Allow-Origin', 'http://localhost:4200');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, 
Content-Type, Accept');
     next();
 })

2 Answers 2

1

You can also try this

let cors = require("cors");

app.use(cors(), function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:4200"); // update to match the domain you will make the request from
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});
Sign up to request clarification or add additional context in comments.

3 Comments

Access to XMLHttpRequest at 'localhost:3000' from origin 'localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I still get the error.
you can use multiple URLs like res.header("Access-Control-Allow-Origin", "http://localhost:4200", "http://localhost:3000");, So can you replace with this one, And please add a browser extension for cors. @RPradhan
@RPradhan is this help you then please do it as marked
0
// Enable CORS
app.use((req, res, next) => {
   // This is how you would enable for ALL incoming requests - I don't recommend
  // res.header("Access-Control-Allow-Origin", "*");

  // Allow multiple [specific] origins - Do it like this
  const allowedOrigins = ["https://my-production-app.com", "http://localhost:4200"];
  const origin = req.headers.origin;
  if (allowedOrigins.indexOf(origin) > -1) {
    res.setHeader("Access-Control-Allow-Origin", origin);
  }

  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.