notElonMusk
notElonMusk

Reputation: 374

Reaching localhost api from hosted static site

Im trying to build a React app on Netlify or Heroku, and reach my local api for testing. I think there's CORs issues when I've tried, just not sure if it's possible.

Any examples of this being done?

Upvotes: 0

Views: 673

Answers (1)

Y.C.
Y.C.

Reputation: 201

yes it's possible

// server.js -> it's your local api
var express = require('express'),
  bodyParser = require('body-parser'),
  app = express(),
  port = process.env.PORT || 4000;

// enable CORS without external module
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();
});

// parse application/json
app.use(bodyParser.json());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// request handlers
app.get('/', (req, res) => {
  res.status(200).json({ message: 'Enable CORS' });
});

app.listen(port, () => {
  console.log('Server started on: ' + port);
});

Start server with: node .\server.js. Open a website on browser. Open developer tools with CTRL+SHIFT+I. Paste the code below into the browser console and see with your own eyes.

// i taked this function from https://stackoverflow.com/a/4033310/19130814
// actually Javascript run on your browser so it's local.
function httpGet(theUrl)
{
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
  xmlHttp.send( null );
  return xmlHttp.responseText;
}

JSON.parse(httpGet("http://localhost:4000/")).message

Upvotes: 1

Related Questions