skip to Main Content

I use Axios to sending request to my NodeJS server. This is my request:

let url = 'http://example.com:1337/api/'

let config = {
    headers: { 
        'Content-Type': 'application/json'
    }
}

settings = (data) => {
    return axios.post(url + 'settings', JSON.stringify(data), config)
    .then( res => res.data)
    .catch(e => console.log(e))
}

In NodeJS/ExpressJS server:

const express = require('express')
const App = express()
let bodyParser = require('body-parser')
// ... Mongoose and etc.

var cors = require('cors')


App.use(cors())
App.options('*', cors());

App.use("/data", express.static(__dirname + '/data'));

App.use(bodyParser.urlencoded({
    extended: true
}));
App.use(bodyParser.json())

App.use('/api', require('./routes/Users'))

App.listen(1337)

But request to http://example.com:1337/api/settings returns (firefox):

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com:1337/api/settings. (Reason: CORS request did not succeed)

Thank you for your solutions.

2

Answers


  1. // server.js
    const express = require('express');
    const app = express();
    
    const routes = require('./routes');
    
    const PORT = process.env.PORT || 5000;
    
    // configure body parser for AJAX requests
    app.use(express.urlencoded({ extended: true }));
    app.use(express.json());
    
    app.use(routes);
    
    //Server
    app.listen(PORT, () => {
        console.log(`Server listening on port ${PORT}.`);
    });
    
    Login or Signup to reply.
  2. Try this:

    const express = require('express')
    const App = express()
    let bodyParser = require('body-parser')
    // ... Mongoose and etc.
      App.all('/*', function(req, res, next) {
              res.header("Access-Control-Allow-Origin", "*");
              res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
              res.header("Access-Control-Allow-Methods", "GET, POST","PUT");
              next();
            });
    
    App.use("/data", express.static(__dirname + '/data'));
    
    App.use(bodyParser.urlencoded({
        extended: true
    }));
    App.use(bodyParser.json())
    
    App.use('/api', require('./routes/Users'))
    
    App.listen(1337)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search