首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用Express框架发出AJAX请求?

如何使用Express框架发出AJAX请求?
EN

Stack Overflow用户
提问于 2013-09-29 13:24:03
回答 3查看 39.4K关注 0票数 20

我想使用Express发送AJAX请求。我运行的代码看起来像下面这样:

代码语言:javascript
复制
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);

我该怎么做呢?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-09-29 13:29:56

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

代码语言:javascript
复制
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();
票数 28
EN

Stack Overflow用户

发布于 2013-09-29 13:27:55

您可以使用request

代码语言:javascript
复制
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.
  }
})
票数 37
EN

Stack Overflow用户

发布于 2015-10-29 06:25:38

由于您只是发出一个get请求,因此我建议您使用此https://nodejs.org/api/http.html#http_http_get_options_callback

代码语言:javascript
复制
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);

});

该代码来自该链接

票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19074727

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档