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=

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


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

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



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>');
type: 'GET',
url: 'http://localhost:3000/api/kfc',
dataType: 'jsonp',
success: function(orders){

$.each(orders, function(i, 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 <


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) {


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");

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


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"

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">
    <meta charset="UTF-8">
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script type="text/javascript">
                .then((res) => {
                    res.json().then((data) => {
                .catch((err) => {
        type: 'GET',
        url: 'http://localhost:8080/kfc',
        dataType: 'json',
        success: function(data) {