Home > Enterprise >  Angular Nodejs Express: ERROR Cross-Origin Request Blocked: Same Origin Policy disallows reading t
Angular Nodejs Express: ERROR Cross-Origin Request Blocked: Same Origin Policy disallows reading t

Time:11-06

I'm trying to post data from angular (on port 4200) to the back-end node.js express server on port 3000.

What I've done so far: I have tried to post the json data from angular to the httpbin.org (a 3rd party server for test use), which proves that my function in angular is valid to post the json data.

Also, I used angular to get data from API of other websites, and they all work, only the nodejs server which is hosted on port 3000 has CORS problem when posting data from angular to it.

I have been googling to change the header of cors for the nodejs server and checked the firewall and lots of other approaches, but nothing works, I always get the CORS error.

**Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:3000/api/postData. (Reason: CORS request did not succeed).**

**ERROR:**
Object { headers: {…}, status: 0, statusText: "Unknown Error", url: "http://127.0.0.1:3000/api/postData", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://127.0.0.1:3000/api/postData: 0 Unknown Error", error: error }
​
error: error { target: XMLHttpRequest, isTrusted: true, lengthComputable: false, … }
​
headers: Object { normalizedNames: Map(0), lazyUpdate: null, headers: Map(0) }
​
message: "Http failure response for http://127.0.0.1:3000/api/postData: 0 Unknown Error"name: "HttpErrorResponse"ok: falsestatus: 0statusText: "Unknown Error"url: "http://127.0.0.1:3000/api/postData"
​
<prototype>: Object { … }

the Angular file: compoent.ts

getData(loc : any) {
  
    //angular --> nodejs
    const headers = new HttpHeaders()
          .set('Authorization', 'my-auth-token')
          .set('Content-Type', 'application/json');

    this.http.post<any>("http://127.0.0.1:3000/api/postData", JSON.stringify(loc)).subscribe(response =>{
      console.log(response);
    }); 

I tried all kinds of headers and cors that I can find on the internet in this Nodejs file but nothing works: app.js

const express = require('express')
const app = express()
const port = 3000
const cors = require('cors')
app.options('*', cors()) // include before other routes 
//app.use(cors())

const corsOpts = {
    origin: '127.0.0.1:3000',
  
    methods: [
      'GET',
      'POST',
    ],
  
    allowedHeaders: [
      'Content-Type',
    ],
  };
  
  app.use(cors(corsOpts));

app.use(function(req, res, next) {
    // res.header("Access-Control-Allow-Origin", "*");
    // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    // next();
    // Website you wish to allow to connect
    res.header('Access-Control-Allow-Origin', '127.0.0.1:3000');
    

    // Request methods you wish to allow
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.header('Access-Control-Allow-Headers', 'Accept, Content-Type, X-Requested-With', 'X-HTTP-Method-Override');

    // 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.header('Access-Control-Allow-Credentials', true);

    if (req.method === 'OPTIONS') {
        res.sendStatus(200);
    } else {
        next();
    }
    });

app.use(
    cors({
      allowedHeaders: ["authorization", "Content-Type"], // you can change the headers
      exposedHeaders: ["authorization"], // you can change the headers
      origin: "*",
      methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
      preflightContinue: false
    })
  );

app.get('/', (req, res, next) => {
    res.send("wtffffffffffffffffff");//send to the page
})

app.get('/getAPIResponse', (req, res, next) => {
    api_helper.make_API_call('https://jsonplaceholder.typicode.com/posts')
    .then(response => {
        res.json(response)
    })
    .catch(error => {
        res.send(error)
    })
})

//angular --> nodejs
app.post('/api/postData',cors(), (req, res, next) => {
    console.log("/postData success when running ng serve");
    console.log(req.body);    
})

app.listen(port, () => console.log(`NodeJS App listening on port ${port}!`))

This is the proxy file : proxy.conf.json

    {
    "/api/*": {
      "target": "http://127.0.0.1:3000",
      "pathRewrite": {"^/api" : ""},
      "secure" : false,
      "changeOrigin" : true
    }
  }

CodePudding user response:

From the docs

Simple Usage (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!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

Get the basic CORS setup working first and then think about battoning down the hatches with some CORS config.

Also remove your proxy config if you are using CORS. Make HTTP requests direct from FE (browser) to your BE server if using CORS.

CodePudding user response:

The problem is simple: I did not run the nodejs server at the backend

  • Related