如何在Express服务器中创建Ajax的GET/POST请求?

8
以下是我的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);
      }
    });
}


可能重复的问题 https://dev59.com/m2Ik5IYBdhLWcg3wqPsi - Muhammad Usman
2
不,那不是我要找的答案。 - Someone
4个回答

10

如何在Node.js Express中进行HTTP GET请求

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


嗨,这解决了我一个关于GET请求的问题;然而,我不知道为什么我无法通过GET请求从这个链接http://jsonplaceholder.typicode.com/comments获取数据,它在http.get()中对/posts有效,但对comments无效,并且如果我在jQuery Ajax的客户端视图中执行它也有效... :/ 你能解释一下吗? - Someone
是的,这是我的本地主机,不知道为什么它会给我404响应 :/ - Someone
首先检查你的 Express 路由名称。在你的路由函数中加入 console.log 来确保它能够到达该路由,然后检查你的查询是否正常工作。 - Enkode
还有其他的错误。它不应该从 file://homepage 加载,而应该是 localhost/homepage。我建议您将所有代码发布到 plunkr 上,以便可以进行审查。 - Enkode
嗨。我已经明白了。我必须在我的jQuery Ajax中将跨域设置为true。 - Someone
显示剩余7条评论

2
你需要了解以下内容:
  1. expressjs 是服务器端代码,所以不能像使用jQuery.ajax那样使用它。
  2. jQuery.ajax() 只能在视图中使用,当你在浏览器中加载页面时。

你需要使用一些视图引擎,比如jade来创建模板,并使用路由器将视图推送到浏览器。当你的视图出现在浏览器中时,你就可以引用包含你的ajax代码的脚本文件,以便你拥有帖子和评论功能。

更多信息。


0

更新 @某人,Express框架在Node中设置Web服务器非常流行。您可以使用不同的渲染引擎来呈现视图并向用户传递信息。这是一个非常简单的示例,从Express网站监听两个URL(/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);
});

如果我想从真实的URL发出请求,我可以在Express中使用什么样的语法? - Someone
在Node中,通常使用http或request模块。请查看我的更新。 - Evers
@Evers那么,根据您的建议,用户在浏览器中输入什么URL才能获得响应呢?我认为路径指示了它需要执行的操作,例如如果您有“/home”,则使用某个视图引擎返回主页视图。 - Jai
啊,现在我明白了混淆的原因。看一下Express,它是一个Web框架。我会用一个例子更新我的答案。 - Evers

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文件调用此函数。在Express服务器上,您只能使用“路由”,并且可以在外部JavaScript文件中对这些路由执行HTTP调用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接