vue.js 如何在本地主机中使用HTTPS运行NUXT(npm run dev)?

mccptt67  于 2023-03-13  发布在  Vue.js
关注(0)|答案(7)|浏览(201)

**编辑:**对案文进行了总体更新,使其更短、更简洁。

当我运行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)/,
        });
      }
    },
  },
};

此外,在这里你可以看到我的依赖包.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
js81xvg6

js81xvg61#

本地开发上的HTTPS- NUXT样式

解决方案如NUXT文档所述:
https://nuxtjs.org/api/configuration-server/#example-using-https-configuration
这可以通过以下方式实现:
1.转到项目主目录;
1.创建私钥和公钥;

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'))
  }
}
w3nuxt5m

w3nuxt5m2#

您必须遵循此处的文档规范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);

现在起作用了!

3xiyfsfu

3xiyfsfu3#

您可以使用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/

qmb5sa22

qmb5sa224#

如果出于某种原因,您像Jan Doleczek所说的那样启用了https,并且还使用了axios模块,请确保在nuxt.config.js中禁用https,如下所示:

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

如果不这样做,所有的axios请求都将使用https而不是https。

jjhzyzn0

jjhzyzn05#

Nuxt 3
选项。不支持来自nuxt.config的服务器。您可以改用--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",
}

我希望我没有丢失示例中的--:-)

a14dhokn

a14dhokn6#

https上本地运行并共享domainsubdomain以共享Single Sign On等的安全Cookie的场景中,请遵循以下步骤
先决条件

  • 开放源码软件
  • 如果您使用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移动到源文件夹的根目录

See more details here

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

  • 根据其他建议的答案,按照Nuxt文档中的更改设置https
  • 输入在步骤1中使用的密码作为密码值
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://subdmain.domain.com:8000)上的https上提供

dvtswwa3

dvtswwa37#

所有的答案似乎都不适用于Nuxt 3,尤其是当当前版本使用defineNuxtConfig作为版本3.2.3时,所以我终于弄清楚了如何使用当前版本。
For Nuxt 3 and using TypeScript
安装fs-extra@types/fs-extra。然后在nuxt.config.ts中

// https://nuxt.com/docs/api/configuration/nuxt-config
import fs from "fs-extra";
export default defineNuxtConfig({
  devServer: {
    host: "vios.uni.edu.my",
    port: 3000,
    https: {
      key: fs.readFileSync("../ssl/private.key").toString(),
      cert: fs.readFileSync("../ssl/cert.crt").toString(),
    },
  },
});

由于密钥keycert需要string类型,我们需要通过toString()将其转换为string

相关问题