如何使用 Express 框架发出 AJAX 请求?
Posted
技术标签:
【中文标题】如何使用 Express 框架发出 AJAX 请求?【英文标题】:How can I make AJAX requests using the Express framework? 【发布时间】: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);
我该怎么做?
【问题讨论】:
【参考方案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();
【讨论】:
文档:nodejs.org/api/http.html#http_http_request_options_callback【参考方案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.
)
【讨论】:
以上是关于如何使用 Express 框架发出 AJAX 请求?的主要内容,如果未能解决你的问题,请参考以下文章
使用 node.js 和 express 的 JQuery Ajax 发布请求
端口 3000 用于 express,端口 8081 用于响应本机,如何发出 get 请求