spa单页面应用history模式后端配置

2 点赞
0 条评论
3169 次浏览
发布于 2021-08-20 20:56

现代化的 web 应用中多数采用 SPA(Single Page Application)的方式来编写网站或者应用,当你的 SPA 的路由方式使用的是 html5 的 history 模式的时候,需要服务器端做相应的配置。

nginx 配置如下:

location / {
  try_files $uri $uri/ /index.html;
}

Apache 配置如下:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

原生 Node.js

const http = require('http')
const fs = require('fs')
const httpPort = 80

http.createServer((req, res) => {
  fs.readFile('index.html', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.html" file.')
    }

    res.writeHead(200, {
      'Content-Type': 'text/html; charset=utf-8'
    })

    res.end(content)
  })
}).listen(httpPort, () => {
  console.log('Server listening on: http://localhost:%s', httpPort)
})

基于 Node.js 的 Express
对于 Node.js/Express,请考虑使用 connect-history-api-fallback 中间件

版权所属:开发日记
转载时必须以链接形式注明原始出处及本声明。
"赞助我们,我们才能做的更多&更好"
赞助支持
还没有评论
写下你的评论...