运行 快速路由中的 http 模块 - NodeJS
Running http module in express route - NodeJS
我想在我的快速路线中呈现一些 HTML 文本。我知道其中一个选项是使用 npm-needle 模块,但我不确定我们是否有任何方法可以在定义的同一路由中使用 npm-express 和 npm-http。
我想要的是这样的:
var http = require("http");
var express = require("express");
var app = express();
app.get("/", function (req, res) {
var params = req.params;
var url = req.query["url"];
let handleRequest = (request, response) => {
response.writeHead(200, {
"Content-Type": "text/plain",
});
response.write("Hi There! " + url);
response.end();
};
});
app.listen(5000);
//http.createServer(handleRequest).listen(8000); ---> not using this in the code
这种类型的东西可能吗?谢谢!
你可以通过 request npm package 轻松完成。
const request = require('request');
app.get("/", function (req, res) {
request('http://www.google.com', function (error, response, body) {
console.error('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response
console.log('body:', body); // Print the HTML for the Google homepage.
});
我不明白为什么你在你的路线中有这个 handleRequest
函数,因为你可以在你的路线中使用这个函数的 req
和 res
inside。
如果您想从您的路线内传送 html,您可以像这样发回 html 文件:
const path = require('path');
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
或者您可以像这样从您的路线中直接发回 html-标签:
app.get("/", function (req, res) {
res.send('<h1>Text</h1>')
});
当然,您可以使用模板字符串等来显示您的数据。
我想在我的快速路线中呈现一些 HTML 文本。我知道其中一个选项是使用 npm-needle 模块,但我不确定我们是否有任何方法可以在定义的同一路由中使用 npm-express 和 npm-http。
我想要的是这样的:
var http = require("http");
var express = require("express");
var app = express();
app.get("/", function (req, res) {
var params = req.params;
var url = req.query["url"];
let handleRequest = (request, response) => {
response.writeHead(200, {
"Content-Type": "text/plain",
});
response.write("Hi There! " + url);
response.end();
};
});
app.listen(5000);
//http.createServer(handleRequest).listen(8000); ---> not using this in the code
这种类型的东西可能吗?谢谢!
你可以通过 request npm package 轻松完成。
const request = require('request');
app.get("/", function (req, res) {
request('http://www.google.com', function (error, response, body) {
console.error('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response
console.log('body:', body); // Print the HTML for the Google homepage.
});
我不明白为什么你在你的路线中有这个 handleRequest
函数,因为你可以在你的路线中使用这个函数的 req
和 res
inside。
如果您想从您的路线内传送 html,您可以像这样发回 html 文件:
const path = require('path');
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
或者您可以像这样从您的路线中直接发回 html-标签:
app.get("/", function (req, res) {
res.send('<h1>Text</h1>')
});
当然,您可以使用模板字符串等来显示您的数据。