【问题标题】:How can I make AJAX requests using the Express framework?如何使用 Express 框架发出 AJAX 请求?
【发布时间】:2013-10-05 03:58:36
【问题描述】:

我想使用 Express 发送 AJAX 请求。我正在运行如下代码:

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

app.get('/', function(req, res) {
   // here I would like to make an external
   // request to another server
});

app.listen(3000);

我该怎么做?

【问题讨论】:

    标签: javascript ajax node.js express


    【解决方案1】:

    由于您只是提出获取请求,因此我建议您这样做 https://nodejs.org/api/http.html#http_http_get_options_callback

    var http = require('http');
    
    http.get("http://www.google.com/index.html", function(res) {
    
      console.log("Got response: " + res.statusCode);
    
      if(res.statusCode == 200) {
        console.log("Got value: " + res.statusMessage);
      }
    
    }).on('error', function(e) {
      console.log("Got error: " + e.message);
    
    });
    

    该代码来自该链接

    【讨论】:

    • 比最佳答案容易得多!
    【解决方案2】:

    您不需要 Express 来发出传出 HTTP 请求。为此使用本机模块:

    var http = require('http');
    
    var options = {
      host: 'example.com',
      port: '80',
      path: '/path',
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': post_data.length
      }
    };
    
    var req = http.request(options, function(res) {
      // response is here
    });
    
    // write the request parameters
    req.write('post=data&is=specified&like=this');
    req.end();
    
    【解决方案3】:

    你可以使用request

    var request = require('request');
    request('http://localhost:6000', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log(body) // Print the body of response.
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2017-05-17
      • 2014-02-04
      • 2015-05-26
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 2012-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多