我已经在 azure 上成功部署了带有 Vue 前端的 Node js ap,但每当您访问非根 URL 时,它都会显示一个白屏,并显示消息“无法获取/products”。

在 Web 服务器的根目录中,我有一个 index.js,它将加载已编译的 vue 前端代码所在的 dist 文件夹的内容: app.use(express.static(__dirname + "/dist"));

我尝试更改我的 web.config 文件,但如果我更改 <action type="Rewrite" url="index.js"/>/dist/index.html ,我的 api 端点停止工作,它基本上只是一个前端。这是我的网络配置文件:

<configuration> 
 <system.webServer> 
 <webSocket enabled="false" /> 
 <handlers> 
  <!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module --> 
  <add name="iisnode" path="index.js" verb="*" modules="iisnode"/> 
</handlers> 
<rewrite> 
  <rules> 
    <!-- Do not interfere with requests for node-inspector debugging --> 
    <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true"> 
      <match url="^index.js\/debug[\/]?" /> 
    </rule> 
 
    <!-- First we consider whether the incoming URL matches a physical file in the /public folder --> 
    <rule name="StaticContent"> 
      <action type="Rewrite" url="public{REQUEST_URI}"/> 
    </rule> 
 
    <!-- All other URLs are mapped to the node.js site entry point --> 
    <rule name="DynamicContent"> 
      <conditions> 
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/> 
      </conditions> 
      <action type="Rewrite" url="index.js"/> 
    </rule> 
  </rules> 
</rewrite> 
<security> 
  <requestFiltering> 
    <hiddenSegments> 
      <remove segment="bin"/> 
    </hiddenSegments> 
  </requestFiltering> 
 </security> 
</system.webServer> 
</configuration> 

`

编辑 - 有关项目设置的更多详细信息

文件夹结构:

根:

/距离:

Index.js:

const contentRoutes = require("./api/content");  
const userRoutes = require("./api/users"); 
const gymRoutes = require("./api/gyms"); 
... 
app.use("/api/content", contentRoutes); 
app.use("/api/users", userRoutes); 
app.use("/api/gyms", gymRoutes); 
... 
app.use(express.static(__dirname + "/dist")); 
 
app.listen(port, () => { 
  console.log("Server is live"); 
}); 

Vue项目中的Router.js:

Vue.use(Router); 
 
export default new Router({ 
 routes: [ 
  { 
   path: "/", 
   name: "index", 
   component: index 
   }, 
  { 
   path: "/gyms/new", 
   component: gymNew 
   }, 
  { 
    path: "/gyms/:id", 
    component: gym 
   }, 
   ... 
  ], 
  mode: "history" 

知道我做错了什么吗?

请您参考如下方法:

const express = require('express') 
const serveStatic = require('serve-static') 
const app = express() 
 
// First serve static pages from dist folder 
var staticPage = serveStatic('dist', {}) 
app.use(staticPage) 

由于是SPA,每次页面刷新或发出新请求时都需要重新路由到index.html

// the regex will check if the request url is not /api then redirect to index.html 
app.get(/^((?!\/api\/).)*$/, function (req, res) { 
    res.sendFile(__dirname + '/dist/index.html') 
}); 


评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!