简单服务器代理一张图片
时间: 2023-09-18 12:11:21 浏览: 46
以下是一个使用 Node.js 搭建的简单服务器代理一张图片的示例:
```js
const http = require('http');
const https = require('https');
const fs = require('fs');
const server = http.createServer((req, res) => {
const imageUrl = 'https://example.com/image.png'; // 要代理的图片 URL
https.get(imageUrl, (response) => {
const { statusCode } = response;
if (statusCode !== 200) {
res.statusCode = statusCode;
res.end();
return;
}
const contentType = response.headers['content-type'];
res.writeHead(200, { 'Content-Type': contentType });
response.pipe(res);
});
});
server.listen(8080, () => {
console.log('Server is running at http://127.0.0.1:8080');
});
```
在上面的示例中,我们创建了一个 HTTP 服务器,然后使用 https.get() 方法获取要代理的图片。如果返回的状态码不是 200,则向客户端返回相同的状态码。否则,我们从响应头中获取内容类型,并将其设置为响应头的 Content-Type 字段。最后,我们将响应主体传输到客户端。您可以使用任何可用的 Node.js 模块来创建服务器代理。