即使在节点服务器中使用npm cors插件后,CORS也会出现问题

时间:2018-10-31 07:56:06

标签: node.js reactjs express redux axios

我已经在节点js中创建了一个简单的服务器来接收来自React应用的请求。

但是对于GET方法,没有CORS错误,但是每当我发布时,都会给我一个错误。

enter image description here

为了使POST方法起作用,我已经在actions文件夹的index.js文件中实现了它,并且应该从server.js文件中找到该网址。

index.js

import axios from 'axios';

export const GET_NAVBAR = "GET_NAVBAR";
export const LOGIN = "LOGIN";

export const BASE_API_URL = "http://localhost:3030";
export const GUEST_API_URL = "https://XXX.XXX.XXX.X:5443/wcs/resources/store/1";


export const getNavbar = () => {
    return axios.get(BASE_API_URL + '/topCategory').then(res => {
        return {
            type: GET_NAVBAR,
            payload: res.data.express.catalogGroupView
        };
    });
};



export const login = () => {
    return axios.post(GUEST_API_URL + '/guestidentity', {}).then(res => {
        console.log(res);
        return {
            type: LOGIN,
            payload: {}
        }
    }).catch(e => {
        console.log(e);
        return {
            type: LOGIN,
            payload: {}
        }
    });
};

server.js

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const Client = require('node-rest-client').Client;//import it here
const app = express();
const helmet = require('helmet');
const morgan = require('morgan');


// enhance your app security with Helmet
app.use(helmet());

// use bodyParser to parse application/json content-type
app.use(bodyParser.json());

app.use(cors());

// log HTTP requests
app.use(morgan('combined'));



app.post('/guestidentity', (req, res) => {

    var client = new Client();

// direct way
    client.post("https://XXX.XXX.XXX.X:5443/wcs/resources/store/1/guestidentity", (data, response) => {
        res.send({express: data});
    });
});



const port = 3030;
app.listen(port, () => console.log(`Server running on port ${port}`));

我不知道我的代码在哪里出错。任何人都可以帮助我解决此问题。如果有人可以提供一些见解或指导我,我将不胜感激。谢谢

2 个答案:

答案 0 :(得分:0)

我曾经用过

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

它将接受任何*来源的信息,您以后可能需要更改

答案 1 :(得分:-1)

在server.js中,添加以下中间件。

var allowCrossDomain = function(req, res, next) {

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

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

res.header('Access-Control-Allow-Headers', 'Content-Type');


next();

};

app.use(allowCrossDomain);