无法在客户端使用带有ajax调用的express运行简单的nodejs服务器

时间:2014-07-15 01:38:49

标签: ajax node.js express

我正在尝试使用express框架创建简单的NodeJS服务器。 在客户端站点,我想使用ajax调用获取数据,但它无法正常工作

我的服务器端代码

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

客户端代码:文件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");
            }
        });
    });

但运行示例后没有任何反应。 控制台显示没有数据。 我在浏览器中输入以下网址来运行此

http://localhost:3000/index.html

代码有什么问题?

谢谢你, 萨钦

1 个答案:

答案 0 :(得分:1)

Express的app.use和app.get如果您指定路径将采取相同的行动,但会按顺序解决。因此,在这种情况下,您的所有请求都将呈现索引页面。请参阅此帖子(Routing with express.js - Cannot GET Error)尝试将json数据更改为另一条路径:

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

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