我该如何使用Express框架发起AJAX请求?

20

我想使用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);

我该如何做到这一点?

3个回答

37

您可以使用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.
  }
})

28

你不需要使用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();

1
文档:https://nodejs.org/api/http.html#http_http_request_options_callback - mauronet

15

由于你只是在进行一个 GET 请求,我建议你使用这个链接: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);

});

那段代码来自于该链接


比最佳答案容易多了! - z3ntu

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