如何使用nodejs编写的API在https上运行

问题描述 投票:0回答:2

我的应用程序具有在svelte js框架中开发的用户和管理界面。他们使用用nodejs编写的API相互通信。整个应用程序部署在一个ec2实例上的AWS上。

安装ssl证书后,用户和管理应用程序以https运行,但API尚未使用https,这就是为什么用户和管理应用程序无法相互通信的原因。

在安装ssl之前,一切正常。

我在aws服务器上运行了nginx。

用户应用程序在端口80上运行:https://www.example.com

Admin application在端口3000上运行:https://www.example.com:3000

API在nodejs中:http://www.example.com:8080

node.js api ssl nginx svelte
2个回答
1
投票

我建议使用nginx作为代理,并在此层中设置SSL证书。含义:nginx将提供SSL证书并处理端口80/443上的所有传入连接。然后,您可以相应地将所有传入流量转发到本地node.js应用程序:

快速示例:

upstream myUIProxy {
  # ip_hash;
  server 127.0.0.1:3000;
  keepalive 8;
}

upstream myAPIProxy {
  # ip_hash;
  server 127.0.0.1:8080;
  keepalive 8;
}

# the nginx server instance

server {
  listen 80;
  listen [::]:80;
  server_name example.com www.example.com;

  return 301 https://example.com$request_uri;
}

server {
  listen 443 ssl;
  listen [::]:443 ssl;
  server_name example.com www.example.com;

  ssl on;
  ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header Host $http_host;
  proxy_set_header X-NginX-Proxy true;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
  proxy_http_version 1.1;
  proxy_set_header Host $host;
  proxy_redirect off;

  location /api {
    proxy_pass http://myAPIProxy/;
  }

  location / {
    proxy_pass http://myUIProxy/;
  }
}

0
投票

HTTPS应用程序无法以默认方式与HTTP api(混合内容)进行通信,这也不安全并且存在一些不良做法。看这里:HTTPS and HTTP CORS

[您可以尝试配置nginx代理,但我建议您仅重新配置您的Node.js api服务器以使用https:

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

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(8000);

更多信息可以在这里找到:

https://nodejs.org/en/knowledge/HTTP/servers/how-to-create-a-HTTPS-server/

© www.soinside.com 2019 - 2024. All rights reserved.