3

I created a REST API in my node.js, express.js application on http://localhost:3000/api/kfc. JSON data is available on it. The function that creates it...

router.get('/kfc', function(req, res, next) {
var response=
{
"id":"123", 
"name":"name1",
"drink":"drink1"
}
res.end(JSON.stringify(response));
});

I am accessing it using jQuery AJAX GET call from http://localhost:8887/kfc.html , The code for kfc.html and kfcLoad.js is-

//kfc.html

<html>
<body>
<h3>Order Placed</h3>
<ul id="ulOrder">

<script src="javascripts/jQuery.js"></script>
<script src="javascripts/kfcLoad.js"></script>
</body>    
</html>

//kfcLoad.js

$(function(){

var $ulOrder=$('#ulOrder');

function addOrder(order)
{
    $ulOrder.append('<li><strong>ID</strong>: '+ order.id+'<br><strong>Name</strong>: '+ order.name+'<br><strong>Drink</strong>: '+order.drink+'<br></li>');
}
$.ajax({
    type: 'GET',
    url: 'http://localhost:3000/api/kfc',
    dataType: 'jsonp',
    success: function(orders){

        $.each(orders, function(i, order){
        addOrder(order);
        });
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(textStatus, errorThrown);
    }
});
});

I am getting errors-

jQuery.js:1 Uncaught SyntaxError: Unexpected token <
kfcLoad.js:1 Uncaught SyntaxError: Unexpected token <
Rahul Chawla
  • 190
  • 1
  • 3
  • 14
  • json and jsonp aren't the same thing. The error you are getting suggests you aren't getting either, and are instead getting likely an error page that returns html. – Kevin B Jun 23 '16 at 19:33
  • Don't use `JSON.stringify` just do `res.json(response)` – eblin Jun 23 '16 at 19:42
  • The HTML page is rendered but the json data is not displayed on it. I don't know exactly what jsonp is but I am using it as I read somewhere to use `dataType: 'jsonp'` as the solution to access from another port. When I wasn't using jsonp I was getting this error- `XMLHttpRequest cannot load http://localhost:3000/api/kfc. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.` – Rahul Chawla Jun 23 '16 at 19:51
  • @eblin It still gives those errors. – Rahul Chawla Jun 23 '16 at 20:08
  • research what jsonp is before using it... wtf – Kevin B Jun 23 '16 at 20:13
  • [What are the differences between JSON and JSONP?](http://stackoverflow.com/questions/2887209/what-are-the-differences-between-json-and-jsonp) – Mikhail Jun 23 '16 at 20:28

1 Answers1

1

On your API Server should be enabled CORS for access from another port. If you use Express.js for enable this you can use https://www.npmjs.com/package/cors module

How to:

npm install cors

And change your

router.get('/kfc', function(req, res, next) {

to

router.get('/kfc', cors(), function(req, res, next) {

Also instead use CORS Module you can use this code

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();
});

And change dataType: 'jsonp' to dataType: 'json'

Example:

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

app.get('/kfc', cors(), function(req, res, next) {
    var response = {
        "id": "123",
        "name": "name1",
        "drink": "drink1"
    }
    res.end(JSON.stringify(response));
});

var port = process.env.PORT || 8080;
app.listen(port, function() {
    console.log('Node.js listening on port ' + port);
});

and example get request

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
    <script type="text/javascript">
    /*fetch('http://localhost:8080/kfc')
                .then((res) => {
                    res.json().then((data) => {
                        console.log(data);
                    });
                })
                .catch((err) => {
                    console.log(err);
                });*/
    $.ajax({
        type: 'GET',
        url: 'http://localhost:8080/kfc',
        dataType: 'json',
        success: function(data) {
            console.log(data)
        }
    });
    </script>
</body>
</html>
Mikhail
  • 11,067
  • 7
  • 28
  • 53
  • I read somewhere to use `dataType: 'jsonp'` as the solution to access from another port. With your solution I was getting `ReferenceError: cors is not defined`, so I included `var cors=require('cors');` but I am still getting those errors. – Rahul Chawla Jun 23 '16 at 19:46
  • @RahulChawla are you can provide all api code? on pastebin for example – Mikhail Jun 23 '16 at 19:48
  • That's the only api code I have. I am providing json data on http://localhost:3000/api/kfc , this json data is being accessed by http://localhost:8887/kfc.html @Mikhail – Rahul Chawla Jun 23 '16 at 20:00
  • Where should I place `app.use(function(req, res, next) {...});`? Inside `router.get('/kfc', function(req, res, next) {...});` – Rahul Chawla Jun 23 '16 at 20:04
  • @RahulChawla are you have a `var app = express();` variable? – Mikhail Jun 23 '16 at 20:12
  • It looks like this `var express = require('express'); var router = express.Router(); cors=require('cors');` – Rahul Chawla Jun 23 '16 at 20:15
  • @RahulChawla try to add `var app = express();` to your code and use cors – Mikhail Jun 23 '16 at 20:17
  • @RahulChawla and change `dataType: 'jsonp'` to `dataType: 'json'` – Mikhail Jun 23 '16 at 20:23
  • @RahulChawla [What are the differences between JSON and JSONP?](http://stackoverflow.com/questions/2887209/what-are-the-differences-between-json-and-jsonp) – Mikhail Jun 23 '16 at 20:28