I am trying to create simple NodeJS server using express framework. and at client site, I wanted to fetch data using ajax call but it's not working
My Server side code
var express = require('express');
var app = express();
function sendJson(req, res){
console.log('User connected');
var jsonEx = '{ "result" :{"name" : "sachin", "surname" : "Tendulkar"}}';
res.type('application/json');
res.send(JSON.stringify(jsonEx));
}
app.use("/",express.static(__dirname));
app.get("/",sendJson);
app.listen(3000);
And client side code : which is the file index.html
$(document).ready(function(){
//Make ajax call to fetch data
$.ajax({
url: "http://localhost:3000/",
type: "GET",
dataType: 'json',
success: function(resp){
console.log(resp);
console.log("Hello");
}
});
});
but nothing happens after running the example. console shows no data. I enter below url in browser to run this
http://localhost:3000/index.html
what is problem with the code ?
Thank you, Sachin
Express's app.use and app.get will act the same if you specify a path, but will resolve in order. So in this case, all your requests are rendering the index page. See this post(Routing with express.js) Try changing the json data to another route like this:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//Make ajax call to fetch data
$.ajax({
url: "http://localhost:3000/data",
type: "GET",
dataType: 'json',
success: function(resp){
console.log(resp);
console.log("Hello");
}
});
});
</script>
</head>
</html>
and
var express = require('express');
var app = express();
function sendJson(req, res){
console.log('User connected');
var jsonEx = '{ "result" :{"name" : "sachin", "surname" : "Tendulkar"}}';
res.type('application/json');
res.send(JSON.stringify(jsonEx));
}
app.use("/",express.static(__dirname));
app.get("/data",sendJson); // defining data as the get endpoint instead of root
app.listen(3000);