ReactJS / NodeJS CORS请求未成功

时间:2018-10-30 11:39:06

标签: node.js reactjs apache axios

我使用Axios将请求发送到我的NodeJS服务器。这是我的要求:

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))
}

在NodeJS / ExpressJS服务器中:

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)

但是对http://example.com:1337/api/settings的请求返回(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)

感谢您的解决方案。

2 个答案:

答案 0 :(得分:0)

// 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}.`);
});

答案 1 :(得分:0)

尝试一下:

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)