Rahul Chawla Rahul Chawla - 5 months ago 16
Ajax Question

jQuery AJAX to access REST API JSON data

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 <

Answer

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>