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:
- app.use(cors())
- the app.use function from here: https://enable-cors.org/server_expressjs.html
- the specific app.use function from here with origin='localhost:4200'
- the app.use function with origin='*'
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);