简体   繁体   English

表示基于路由的静态文件URL更改

[英]Express static files URL changes based on route

I have create-react-app thats using react-router-dom. 我有使用react-router-dom的create-react-app。 I'm also using express server-side-rendering for SEO. 我还在SEO中使用快速服务器端渲染。 Below is my simple express config. 下面是我的简单表达配置。 When I got to the '/' route or any of the first-level routes ("/contact", "/blog", etc), it works as intended. 当我到达“ /”路线或任何一级路线(“ / contact”,“ / blog”等)时,它都可以正常工作。 The static files come in as: 静态文件来自:

" http://localhost:8080/static/css/main.ec91a01d.css ". http:// localhost:8080 / static / css / main.ec91a01d.css ”。

But when I navigate to any multi-level routes ("/blog/blog-post-1"), it adds the first route to the static files URl ex: 但是,当我导航到任何多级路由(“ / blog / blog-post-1”)时,它将第一条路由添加到静态文件URl ex中:

http://localhost:8080/blog/static/js/main.d9a1d852.js http:// localhost:8080 / blog / static / js / main.d9a1d852.js

What am I doing wrong? 我究竟做错了什么? Also, the folder structure is that of a regular Create-react-app. 此外,文件夹结构是常规Create-react-app的结构。 Im serving my index.html from the build folder and my styles/js from build/static. 我从build文件夹提供index.html,从build / static提供样式/ js。

Project
----build
----public
...etc

And my server.js 还有我的server.js

const express = require('express');
const path = require('path');
const ssr = require('./ssr.mjs');

const app = express();

const crawler = async (req, res) => {
  const isBot = req.get('User-Agent').indexOf('Googlebot') > -1 || 
  req.get('User-Agent').indexOf('googlebot') > -1;
  if (isBot) {
    const { html } = await ssr(`http://www.example.com${req.path}`);
    return res.status(200).send(html);
  }
  res.sendFile(path.join(__dirname + '/build/index.html'));
};
app.use(express.static('build'));
app.get('/', crawler);

app.get('/process', crawler);
app.get('/work', crawler);
app.get('/contact', crawler);
app.get('/blog', crawler);
app.get('/blog/create-post', crawler);
app.get('/blog/:id', crawler);
app.get('/services', crawler);
app.get('/services/:id', crawler);
app.get('/payments', crawler);



const PORT = process.env.PORT || 8080;

app.listen(PORT, () => console.log('Server started. Press Ctrl+C to quit'));

You seem to be fetching your ressources with relative paths in your index.html , eg 您似乎正在使用index.html相对路径来获取资源,例如

<script src="./static/js/main.d9a1d852.js"></script>

What you want are absolute paths: 您想要的是绝对路径:

<script src="/static/js/main.d9a1d852.js"></script>

Notice the missing . 注意丢失的内容. at the beginning of the path. 在路径的开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM