温馨提示×

如何在CentOS上配置Node.js代理

小樊
44
2025-11-25 19:12:58
栏目: 编程语言

在CentOS上配置Node.js代理,通常是指设置Node.js应用程序的HTTP代理。这可以通过多种方式实现,包括使用环境变量、在代码中直接设置或者使用第三方库。以下是一些常见的方法:

方法1:使用环境变量

你可以在启动Node.js应用程序之前设置HTTP_PROXYHTTPS_PROXY环境变量。

export HTTP_PROXY=http://proxyserver:port
export HTTPS_PROXY=https://proxyserver:port
node app.js

如果你需要代理认证,可以在URL中包含用户名和密码:

export HTTP_PROXY=http://username:password@proxyserver:port
export HTTPS_PROXY=https://username:password@proxyserver:port

方法2:在代码中设置

在你的Node.js应用程序中,你可以使用httphttps模块来设置代理。

const http = require('http');
const https = require('https');

const options = {
  hostname: 'example.com',
  port: 80,
  path: '/',
  method: 'GET',
  headers: {
    'Content-Type': 'application/json'
  },
  // 代理设置
  agent: new (require('https').Agent)({
    host: 'proxyserver',
    port: port,
    auth: 'username:password', // 如果需要代理认证
    protocol: 'http:',
  })
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

req.end();

方法3:使用第三方库

有许多第三方库可以帮助你更容易地设置代理,例如axiosgot

使用axios设置代理:

const axios = require('axios');

const instance = axios.create({
  proxy: {
    host: 'proxyserver',
    port: port,
    auth: {
      username: 'username',
      password: 'password'
    }
  }
});

instance.get('http://example.com').then(response => {
  console.log(response.data);
});

使用got设置代理:

const got = require('got');

(async () => {
  try {
    const response = await got('http://example.com', {
      proxy: {
        host: 'proxyserver',
        port: port,
        protocol: 'http:',
        // 如果需要代理认证
        credentials: 'username:password'
      }
    });
    console.log(response.body);
  } catch (error) {
    console.error(error);
  }
})();

方法4:使用noproxy环境变量

如果你有一些内部请求不需要通过代理,你可以设置NO_PROXY环境变量。

export NO_PROXY=localhost,127.0.0.1,.example.com

这样,对于列出的主机和域名,请求将不会通过代理服务器。

确保在配置代理之前,你已经安装了Node.js和npm,并且你的应用程序可以在没有代理的情况下正常运行。配置代理后,你应该测试应用程序以确保代理设置正确无误。

0