node.js 如何使用 Express 框架发出 AJAX 请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19074727/
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-09-02 15:47:57  来源:igfitidea点击:

How can I make AJAX requests using the Express framework?

javascriptajaxnode.jsexpress

提问by codeofnode

I want to send AJAX requests using Express. I am running code that looks like the following:

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

How would I do this?

我该怎么做?

回答by Alexander Kobelev

You can use requestlibrary

您可以使用请求

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

回答by hexacyanide

You don't need Express to make an outgoing HTTP request. Use the native module for that:

您不需要 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();

回答by Tony

Since you are simply making a get request I suggest this https://nodejs.org/api/http.html#http_http_get_options_callback

由于您只是提出获取请求,因此我建议使用 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);

});

That code is from that link

该代码来自该链接