簡體   English   中英

如何在本地主機中使用 HTTPS 運行 NUXT(npm run dev)?

[英]How to run NUXT (npm run dev) with HTTPS in localhost?

編輯:總體上更新了文本以使其更短更簡潔。

我在運行npm run dev時嘗試配置 HTTPS,以便我可以在本地測試 MediaStream 等(瀏覽器要求我提供 HTTPS)。

我正在嘗試通過 nuxt.config.js 配置它,但沒有任何成功。

這是我的 nuxt.config.js 文件:

import fs from "fs";
import pkg from "./package";

export default {
  mode: "spa",

  /*
  ** Headers of the page
  */
  head: {
    title: pkg.name,
    meta: [
      { charset: "utf-8" },
      { name: "viewport", content: "width=device-width, initial-scale=1" },
      { hid: "description", name: "description", content: pkg.description },
    ],
    link: [
      { rel: "icon", type: "image/x-icon", href: "/favicon.ico" },
    ],
  },

  /*
  ** Customize the progress-bar color
  */
  loading: { color: "#fff" },

  /*
  ** Global CSS
  */
  css: [
    "element-ui/lib/theme-chalk/index.css",
    "@makay/flexbox/flexbox.min.css",
  ],

  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
    "@/plugins/element-ui",
    "@/plugins/vue-upload",
    "@/plugins/axios-error-event-emitter",
    "@/plugins/eventemitter2",
    "@/plugins/vue-awesome",
    "@/plugins/webrtc-adapter",
    "@/plugins/vue-browser-detect-plugin",
  ],

  /*
  ** Nuxt.js modules
  */
  modules: [
    // Doc: https://axios.nuxtjs.org/usage
    "@nuxtjs/axios",
    "@nuxtjs/pwa",
  ],
  /*
  ** Axios module configuration
  */
  axios: {
    // See https://github.com/nuxt-community/axios-module#options
    baseURL: process.env.NODE_ENV === "production" ? "https://startupsportugal.com/api/v1" : "http://localhost:8080/v1",
  },

  /*
  ** Build configuration
  */
  build: {
    transpile: [/^element-ui/, /^vue-awesome/],

    filenames: {
      app: ({ isDev }) => (isDev ? "[name].[hash].js" : "[chunkhash].js"),
      chunk: ({ isDev }) => (isDev ? "[name].[hash].js" : "[chunkhash].js"),
    },

    /*
    ** You can extend webpack config here
    */
    extend(config, ctx) {
      // Run ESLint on save

      if (ctx.isClient) config.devtool = "#source-map";

      if (ctx.isDev) {
        config.devServer = {
          https: {
            key: fs.readFileSync("server.key"),
            cert: fs.readFileSync("server.crt"),
            ca: fs.readFileSync("ca.pem"),
          },
        };
      }

      if (ctx.isDev && ctx.isClient) {
        config.module.rules.push({
          enforce: "pre",
          test: /\.(js|vue)$/,
          loader: "eslint-loader",
          exclude: /(node_modules)/,
        });
      }
    },
  },
};

此外,在這里您可以在 package.json 中看到我的依賴項:

"dependencies": {
    "@makay/flexbox": "^3.0.0",
    "@nuxtjs/axios": "^5.3.6",
    "@nuxtjs/pwa": "^2.6.0",
    "cross-env": "^5.2.0",
    "element-ui": "^2.4.11",
    "eventemitter2": "^5.0.1",
    "lodash": "^4.17.11",
    "nuxt": "^2.8.0",
    "pug": "^2.0.3",
    "pug-plain-loader": "^1.0.0",
    "quagga": "^0.12.1",
    "stylus": "^0.54.5",
    "stylus-loader": "^3.0.2",
    "vue-awesome": "^3.5.3",
    "vue-browser-detect-plugin": "^0.1.2",
    "vue-upload-component": "^2.8.20",
    "webrtc-adapter": "^7.2.4"
  },
  "devDependencies": {
    "@nuxtjs/eslint-config": "^0.0.1",
    "babel-eslint": "^10.0.1",
    "eslint": "^5.15.1",
    "eslint-config-airbnb-base": "^13.1.0",
    "eslint-config-standard": ">=12.0.0",
    "eslint-import-resolver-webpack": "^0.11.1",
    "eslint-loader": "^2.1.2",
    "eslint-plugin-import": ">=2.16.0",
    "eslint-plugin-jest": ">=22.3.0",
    "eslint-plugin-node": ">=8.0.1",
    "eslint-plugin-nuxt": ">=0.4.2",
    "eslint-plugin-promise": ">=4.0.1",
    "eslint-plugin-standard": ">=4.0.0",
    "eslint-plugin-vue": "^5.2.2",
    "nodemon": "^1.18.9"
  }

但是,當我運行npm run dev它仍然不提供 HTTPS,但也不提供任何錯誤輸出......

輸出與我在 nuxt.config.js 中沒有 HTTPS 配置完全相同:

$ npm run dev

> clothing-demo@1.0.0 dev /mnt/d/tralha/clothing-demo-app/frontend
> nuxt --hostname 0.0.0.0 --port 3000


   ╭────────────────────────────────────────────────╮
   │                                                │
   │   Nuxt.js v2.8.1                               │
   │   Running in development mode (spa)            │
   │                                                │
   │   Listening on: http://192.168.126.241:3000/   │
   │                                                │
   ╰────────────────────────────────────────────────╯

ℹ Preparing project for development                                                                                                                                                                                  14:30:34
ℹ Initial build may take a while                                                                                                                                                                                     14:30:35
✔ Builder initialized                                                                                                                                                                                                14:30:35
✔ Nuxt files generated                              

本地開發的 HTTPS - NUXT 風格

NUXT 文檔中描述了解決方案:

https://nuxtjs.org/api/configuration-server/#example-using-https-configuration

這可以通過以下方式實現:

  1. 轉到項目主目錄;
  2. 創建私鑰和公鑰;
openssl genrsa 2048 > server.key
chmod 400 server.key
openssl req -new -x509 -nodes -sha256 -days 365 -key server.key -out server.crt
  1. nuxt.config.js頂部添加需求;
import path from 'path'
import fs from 'fs'
  1. nuxt.config.js 中擴展或添加服務器配置;
server: {
  https: {
    key: fs.readFileSync(path.resolve(__dirname, 'server.key')),
    cert: fs.readFileSync(path.resolve(__dirname, 'server.crt'))
  }
}

您必須遵循此處的文檔規范https://nuxtjs.org/api/configuration-server/#example-using-https-configuration ,但您必須在server/index.js文件中添加代碼,否則它將無法工作根本。

所以在server/index.js的頂部添加const https = require('https')並替換:

app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })

https.createServer(nuxt.options.server.https, app).listen(port, host);

現在它開始工作了!

如果由於某種原因你像 Jan Doleczek 所說的那樣啟用了 https 並且你也使用了 axios 模塊,請確保在 nuxt.config.js 中禁用 https:

  axios: {
    baseURL: 'http://yourapi:8000',
    https:false,
  },

如果您不這樣做,您的所有 axios 請求都將使用 https 而不是 https。

您可以使用mkcert

  1. 安裝 mkcert:
brew install mkcert
brew install nss # if you use Firefox
  1. 將 mkcert 添加到您的本地根 CA:
mkcert -install
  1. 在您的終端中,導航到您站點的根目錄或您希望證書所在的任何目錄。 並運行:
mkcert localhost
  1. 將以下內容添加到您的nuxt.config.js
    server: {
        https: {
            key: fs.readFileSync(path.resolve(__dirname, 'localhost-key.pem')),
            cert: fs.readFileSync(path.resolve(__dirname, 'localhost.pem'))
        }
    }

https://web.dev/how-to-use-local-https/

https上運行本地並共享domainsubdomain以共享用於Single Sign On等的安全 cookie 的場景中,請遵循以下步驟

先決條件

  • openssl
    • 如果您使用的是 Windows,您可以在C:\\Program Files\\Git\\usr\\bin找到openssl.exe
  • 您的 .pfx 證書
    • 如果需要,包括密碼

1. 使用 openssl.exe 創建 .crt 和 .key 文件

1.1 創建密鑰

  • pkcs12 -in '[full-path-and-name-of-your].pfx' -nocerts -out '[full-path-and-name-to-create-the].key'
  • 如果提示輸入密碼以打開您的 .pfx

1.2 創建crt

  • pkcs12 -in '[full-path-and-name-of-your].pfx' -clcerts -nokeys -out '[full-path-and-name-to-create-the].crt'
  • 將 .key 和 .crt 移動到源文件夾的根目錄

在此處查看更多詳細信息

2. 可能在nuxt.config.js更新server配置

  • 正如其他答案所建議的那樣,按照Nuxt 文檔中的更改設置 https
  • 輸入在步驟 1 中使用的密碼作為 passphase 值
  server: {
    https: {
      key: fs.readFileSync(path.resolve(__dirname, '[key-file-name].key')),
      cert: fs.readFileSync(path.resolve(__dirname, '[crt-file-name].crt')),
      passphrase: '[your password]'
    }
  }

3. 創建/修改本地構建腳本以指定主機名

"dev": "nuxt --hostname subdmain.domain.com --port 8000"

您的本地現在將在該域/子域和端口上的 https 上提供服務,例如https://subdmain.domain.com:8000

Nuxt 3

不支持來自nuxt.config options.server。 您可以改用--port, --host, --https, --ssl-cert--ssl-key

官方文檔

像這樣的東西:

{
    "scripts": {
        "dev": "nuxi dev --host website.test --https --ssl-key key.pem --ssl-cert cert.pem --port 3000",
}

我希望我沒有輸--例如:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM