I have created a simple server in node js to take the request from a react app.
But for the GET method there is no CORS error but whenever I do post, it gives me an error.
For the POST method to work, I have implemented in index.js file of the actions folder and it should hit the url from the server.js file.
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 hereconst app = express();const helmet = require('helmet');const morgan = require('morgan');// enhance your app security with Helmetapp.use(helmet());// use bodyParser to parse application/json content-typeapp.use(bodyParser.json());app.use(cors());// log HTTP requestsapp.use(morgan('combined'));app.post('/guestidentity', (req, res) => {var client = new Client();// direct wayclient.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}`));
I don't know where my code is getting wrong. Can anybody please help me to troubleshoot this issue. I would be grateful if someone could provide an insight or guide me a little. Thanks
Best Answer
For my part I used
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();});
It will accept from any *
sources, you might want to change that later
In your server.js , add the following middleware.
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);