【问题标题】:How to make ajax get/post request in express server?如何在快速服务器中进行 ajax 获取/发布请求?
【发布时间】:2016-01-03 00:04:21
【问题描述】:

下面是我的快递服务器。我正在尝试在 ajax 中发出 get 请求,但即使我一开始就需要 jquery,它也失败了。它说 $ 没有定义 除了使用 jquery ajax,我还能用什么来进行 API 调用表单 RESTful API url?

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

【问题讨论】:

标签: javascript jquery ajax express


【解决方案1】:

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

【讨论】:

  • 您好,解决了我的一个获取请求问题;但是,我不知道为什么我没有通过此链接jsonplaceholder.typicode.com/comments 获取请求获取数据,它适用于 http.get() 中的 /posts,但不适用于 cmets,如果我这样做它也适用它在 jquery ajax 的客户端视图中...:/你能解释一下吗?
  • 可能有多种原因,CORS,不正确的标题...您发布到哪个服务器?它是您自己的本地主机吗?您需要检查响应以查看服务器是否响应错误。
  • 是的。这是我的本地主机,不知道为什么它会给我 404 响应:/
  • 首先检查您的快速路线名称。在你的路由函数中放入一个 console.log 以确保它进入路由,然后检查以确保你的查询正常工作。
  • 只要确认是路由即可。谢谢:D
【解决方案2】:

您需要了解以下内容:

  1. expressjs 是服务器端代码,所以它不能像那样使用 jquery ajax。
  2. jQuery.ajax() 只能在您在浏览器中加载页面时在视图中使用。

您需要使用jade 等一些视图引擎来创建模板并使用路由器将视图推送到浏览器中。当您在浏览器中查看视图时,您可以引用包含您的 ajax 代码的脚本文件,以让您拥有帖子和 cmets。

More information.

【讨论】:

    【解决方案3】:

    试试这样的:

    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 调用。

    【讨论】:

      【解决方案4】:

      更新 @Someone,express 框架在 Node.js 中设置 Web 服务器非常流行。您可以使用不同的渲染引擎来渲染视图并将信息传递给用户。这是来自 Express 网站的一个非常简单的示例,它监听两个 url(/posts 和 /cmets)。

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

      【讨论】:

      • 所以如果我想从一个真实的 url 发出请求,我可以在 express 中使用什么样的语法?
      • 在 Node 中你通常使用 http 或 request 模块。查看我的更新。
      • @Evers 那么用户必须在浏览器中键入什么才能按照您的建议获得响应。在我看来,如果您有/home,该路径会建议它必须执行的操作,它会使用某些视图引擎返回主视图。
      • 啊,现在我有点困惑了。看看 Express,express 是一个 web 框架。我会用一个例子来更新我的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多