0

Im trying to enable CORS on a localhost site for a Node.js server with an Angular client.

I keep getting:

Access to XMLHttpRequest at 'localhost:3000/api/v1/users' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

I've tried:

My current node server.js file:

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

const port = 3000

///////
app.use(cors());

app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
});

///////
app.get('/*', (request, response) => {
  response.send('Hello from Express!')
})

app.listen(port, (err) => {
  if (err) {
    return console.log('something bad happened', err)
  }

  console.log(`server is listening on ${port}`)
})

My Angular method that is calling the node route (I know this is working because I get the cors error in chrome console shown above):

this.http.get<string[]>('localhost:3000/'+'api/v1/users').subscribe(x=>this.data=x);
Rilcon42
  • 9,584
  • 18
  • 83
  • 167
  • Add the proxy settings like: https://juristr.com/blog/2016/11/configure-proxy-api-angular-cli/ – Sudhakar Apr 05 '19 at 05:57
  • 1
    Use `this.http.get('http://localhost:3000/'+'api/v1/users').subscribe(x=>this.data=x)` (with `http://` protocol part included) instead of just `this.http.get('localhost:3000/'+'api/v1/users').subscribe(x=>this.data=x)` – sideshowbarker Apr 05 '19 at 05:58
  • @Sudhakar that solution worked for me. Want to write it up and propose it as an answer? – Rilcon42 Apr 05 '19 at 20:20

1 Answers1

0

For testing you should use a CORS browser plugin. The benefit of this is, that you dont have to modify the code when you want to build the code for prod

scrach
  • 21
  • 4