access to xmlhttprequest from origin http://localhost:3000 has been blocked due to CORS policy

Viewed 2788

i have set a front and a backend for an app i am developing and i want to test http requests sent from front to back while these two run in localhost.

Code sending request using React:

 async componentDidMount(){
           const {data: posts}= await axios.get("localhost:8765/...");
       }

Code for app server using Express:

const express = require('express')
const app = express()
require('./routes/...')(app)

app.listen(8765, () => {
    console.log("Server is listening on port 8765.")
})

Front end is running on localhost 3000.

This is the error i get:

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

i have tried various solutions i found online like:

var cors = require('cors');

app.use(cors({origin: 'http://localhost:3000'}));

or:

app.use(function (req, res, next) {

    
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

    
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    
    res.setHeader('Access-Control-Allow-Credentials', true);

    
    next();
});

or:

app.use(cors())

Nothing seems to work though,i still get the same error,and i've been stuck in this for quite a while.Any ideas?

1 Answers

Simply use res.setHeader('Access-Control-Allow-Origin', '*');

Related