0

I know there is no shortage of CORS questions on SO but none could help me in this circumstances:

I'd like to get JSON data from localhost backend using this jQuery snippet:

var SERVER_URL = "http://127.0.0.1:8080";

$.getJSON(SERVER_URL,function(result){
    console.log("result is", result);
  $.each(result, function(i, field){
    $("div").append(field + " ");
      });
    });

The snippet is loaded to index.html which is run on http://localhost:3000/index.html using this simple node static-file server:

var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(3000, function(){
    console.log('Server running on 3000...');
});

But in Chrome console I get:

Failed to load http://127.0.0.1:8080/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

I had the same issue in Firefox.

How can I fix this?

Babr
  • 1,971
  • 14
  • 33
  • 47

2 Answers2

0

install cors package

npm install cors

and use like this

var cors = require('cors');

const corsOptions = {
  methods: "GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE",  // use to manage api cross origin error
  origin: '*'
}

OR

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

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

Run This Command it will open new chrome and run your code here

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39
0

You should set header Access-Control-Allow-Origin: * at your server. The way you should do is depend with your server side language.

Ex: PHP

<?php
header('Access-Control-Allow-Origin: *'); 
?>