Some Guy
Some Guy

Reputation: 401

CORS in a restify server is giving me trouble

I have a RESTIFY api up and running on a Raspberry pi. It's IP is static at 192.168.1.12. I also want to run a web server from create-react-app that I can access that grabs information from the api.

create-react-app:

axios.get(`http://localhost:8080/ping`).then(
    (response) => {
        console.log(`response received!`);
    }
).catch(
    (error) => {
        console.error(`error received from axios`);
    }
);

RESTify (when setting up the server):

const corsMiddleware = require('restify-cors-middleware');
const cors = corsMiddleware(
    {
        origins: [
            '*'
        ]
    }
);
server.pre(cors.preflight);
server.use(cors.actual);
server.get(`/ping`, (req, res) => res.send(200));

Yet I still cannot get the create-react-app to get through to the server. What am I doing wrong here?

Upvotes: 0

Views: 459

Answers (3)

Some Guy
Some Guy

Reputation: 401

restify on port 8080:

const corsMiddleware = require('restify-cors-middleware');

const cors = corsMiddleware({origins: ['*']});
server.pre(cors.preflight);
server.use(cors.actual);
server.get('/ping', (req, res) => { console.log('pinged'); res.send(200, 'hello') });

CRA on port 3000:

File package.json:

"proxy": "http://localhost:8080"

File App.js:

fetch('/ping', { accept: 'application/json' }).then(data => data.json()).then(json => console.log(json));

Source: Here

Upvotes: 0

Nisha
Nisha

Reputation: 1

 res.header('Access-Control-Allow-Origin', 'localhost'); //replace localhost with actual host
    res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, PUT, PATCH, POST, DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization');

Upvotes: 0

Ankit Kumar Rajpoot
Ankit Kumar Rajpoot

Reputation: 5600

If you are using Expressjs then You can use.

npm install cors
var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

Or You can use middleware

//CORS middleware
var corsMiddleware = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'localhost'); //replace localhost with actual host
    res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, PUT, PATCH, POST, DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization');

    next();
}

app.use(corsMiddleware); 

Upvotes: 1

Related Questions