如何在快递服务器上进行ajax get / post请求?

时间:2015-10-06 07:04:38

标签: javascript jquery ajax express

以下是我的快递服务器。我试图在ajax中发出get请求,但结果却失败了,即使我在开始时需要jquery。它说$没有定义除了使用jquery ajax之外,我还可以使用什么来从RESTful API url进行API调用?

var express = require('express');
var requestHandler = require('./requestHandler');
var app = express();
var path = require('path');


app.use(express.static(path.join(__dirname, '../client')));
app.get('/homepage', requestHandler.getData);

var port = process.env.PORT || 3000;
app.listen(port);
console.log("Server running at: http://localhost:" + port);

// request handler file:

var express = require('express');
var url = "http://jsonplaceholder.typicode.com/";

module.exports.getData = function (req, res){
    $.ajax({
      method: 'GET',
      url: url+'posts',
      success: function(data) {
        console.log(data);
        res.send(data);
      }
    });
  }
module.exports.getComments = function(userId){
    $.ajax({
      method: 'GET',
      url: url+'/comments',
      success: function(data) {
        console.log(data);
      }
    });
}

4 个答案:

答案 0 :(得分:9)

HTTP GET Request in Node.js Express

var http = require('http');
var options = {
  host: 'www.google.com',
  path: '/index.html'
};

var req = http.get(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));

  // Buffer the body entirely for processing as a whole.
  var bodyChunks = [];
  res.on('data', function(chunk) {
    // You can process streamed parts here...
    bodyChunks.push(chunk);
  }).on('end', function() {
    var body = Buffer.concat(bodyChunks);
    console.log('BODY: ' + body);
    // ...and/or process the entire body here.
  })
});

req.on('error', function(e) {
  console.log('ERROR: ' + e.message);
});

答案 1 :(得分:1)

您需要了解以下内容:

  1. expressjs是服务器端代码,所以它不能像这样使用jquery ajax。
  2. jQuery.ajax()只能在浏览器中加载页面时在视图中使用。
  3. 您需要使用某些视图引擎(如jade)来创建模板并使用路由器在浏览器中推送视图。当您在浏览器中查看视图时,您可以对脚本文件进行引用,该脚本文件可以包含您的ajax代码,以便您拥有帖子和注释。

    More information.

答案 2 :(得分:0)

<强>更新 @Someone,快速框架在Node中设置Web服务器非常流行。您可以使用不同的渲染引擎来渲染视图并将信息传递给用户。这是一个非常简单的例子,来自Express网站,听取两个网址(/ posts和/ comments)。

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

app.get('/posts', function (req, res) {
  res.send('Render posts!');
});

app.get('/comments', function (req, res) {
  res.send('Render comments');
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});

答案 3 :(得分:0)

尝试这样的事情:

function() {


    // Simple POST request example (passing data) :
    $http.post("/createProject/"+ id +"", {
        projectTitle: pTitle,
        userID      : id
    }).
    success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        $scope.getProjects();
        console.log("project created");
        console.log("this is the response data " + data);
    }).
    error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
    });
 };

另请注意。你将从外部JavaScript文件中调用它。快递服务器只有“路由”,外部javascript文件可以在这些路由上执行HTTP调用。