[英]Node.js express send raw HTTP responses
I have a legacy system that can return raw\plain HTTP responses as a string (text that contains all the required headers + body).我有一个遗留系统,可以将原始\plain HTTP 响应作为字符串返回(包含所有必需标头+正文的文本)。
I would like to send this text directly without any parsing modifications for performance reasons.出于性能原因,我想直接发送此文本而不进行任何解析修改。
So goal is to proxy received raw HTTP response.所以目标是代理收到的原始 HTTP 响应。
const express = require('express');
const app = express();
const router = app.Router();
router.get('request',()=>{
const plainTextWithHeadersFromExternalSystem = `HTTP/1.1 200 OK
Date: Sun, 10 Oct 2010 23:26:07 GMT
Server: Apache/2.2.8 (Ubuntu) mod_ssl/2.2.8
OpenSSL/0.9.8g
Last-Modified: Sun, 26 Sep 2010 22:04:35 GMT
ETag: "45b6-834-49130cc1182c0"
Accept-Ranges: bytes
Content-Length: 12
Connection: close
Content-Type: text/html
Hello world!`;
... TODO: send text with headers and body as a response.
});
It can be any content type, not only a plain text.它可以是任何内容类型,而不仅仅是纯文本。
Any ideas whether it's possible to simply proxy it with the Node.js express lib?任何想法是否可以简单地使用 Node.js express lib 代理它?
I had the same problem myself and had to dive deeper into Node's core http
and net
modules to figure it out.我自己也遇到了同样的问题,不得不深入研究 Node 的核心http
和net
模块来解决这个问题。
To skip the default HTTP response line ( eg HTTP/1.1 200 OK
) and all of the headers that Express/Node.js send, you can send your text directly through the response's socket .要跳过默认的 HTTP 响应行(例如HTTP/1.1 200 OK
)和 Express/Node.js 发送的所有标头,您可以直接通过响应的 socket发送文本。
const responseMessage = `HTTP/1.1 200 OK
Date: Sun, 10 Oct 2010 23:26:07 GMT
Content-Type: text/html
Content-Length: 13
Hello, World!
`
router.get('/request', (req, res) => {
res.socket.end(responseMessage)
})
you can use following to set headers您可以使用以下设置标题
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
// extra headers here
})
or you use或者你使用res.header(field, [value])
complete code can be like this完整的代码可以是这样的
router.get('request', (req, res) => {
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
// extra headers here
});
res.send('Hello world!');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.