Javascript 如何在快递服务器中进行ajax获取/发布请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32963736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:26:22  来源:igfitidea点击:

How to make ajax get/post request in express server?

javascriptjqueryajaxexpress

提问by Someone

Below is my express server. I am trying to make a get request in ajax, but it turned out failed even though I required jquery at the beginning. It said $ is not defined Other than using jquery ajax, what else can I use to make an API call form RESTful API url?

下面是我的快递服务器。我试图在 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);
      }
    });
}

回答by Enkode

HTTP GET Request in Node.js Express

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

回答by Jai

You need to understand things like:

您需要了解以下内容:

  1. expressjsis serverside code so it can't use jquery ajax like that.
  2. jQuery.ajax()can only be used at view when you load your page in the browser.
  1. expressjs是服务器端代码,所以它不能像那样使用 jquery ajax。
  2. jQuery.ajax()只能在浏览器中加载页面时在视图中使用。


You need to use some view engines like jadeto create templates and use routers to push the view in the browser. When you have your view in the browser then you can make a reference to the script file which can contain your ajax code to let you have posts and comments.

您需要使用一些视图引擎,例如jade创建模板并使用路由器在浏览器中推送视图。当您在浏览器中拥有视图时,您可以引用脚本文件,该文件可以包含您的 ajax 代码,以便您拥有帖子和评论。

More information.

更多信息。

回答by Skywalker

Try something like this:

尝试这样的事情:

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

Also please note. you will call this from an external JavaScript file. One the express server you will only have "routes" and from external javascript files you can perform HTTP calls on those routes.

还请注意。您将从外部 JavaScript 文件调用它。一个 Express 服务器,您将只有“路由”,并且您可以从外部 javascript 文件对这些路由执行 HTTP 调用。

回答by Evers

Update@Someone, the express framework is very popular to setup a web server in Node. You can use different render engines to render the view and pass information to the user. This is a very simple example from the Express website listening to two urls (/posts and /comments).

更新@Someone,express 框架非常流行用于在 Node.js 中设置 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);
});