[英]how to load images in server side rendering in react?
I have this code in my server/server.js我的 server/server.js 中有这段代码
import path from 'path';
import fs from 'fs';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import express from 'express';
import App from '../src/App';
const PORT = process.env.PORT || 1234;
const app = express();
// ...
app.get('/', (req, res) => {
const app = ReactDOMServer.renderToString(<App />);
const indexFile = path.resolve('./build/index.html');
fs.readFile(indexFile, 'utf8', (err, data) => {
if (err) {
console.error('Something went wrong:', err);
return res.status(500).send('Oops, better luck next time!');
}
return res.send(
data.replace('<div id="root"></div>', `<div id="root">${app}</div>`)
);
});
});
app.use(express.static('./build'));
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
Also server/index.js还有 server/index.js
require('ignore-styles')
require('@babel/register')({
ignore: [/(node_module)/],
presets: ['@babel/preset-env', '@babel/preset-react']
})
require('./server')
While running in port the images are not loading css is rendering in server side.在端口中运行时,图像未加载css 在服务器端呈现。
React version : 17反应版本:17
I have also hydrated in index.js我还在 index.js 中补充了水分
Any answer will be a great help .任何答案都会有很大帮助。
Thank You.谢谢你。
I found a solution我找到了解决方案
create a images folder then add this line创建一个图像文件夹,然后添加这一行
app.use('/images', express.static(path.join(__dirname, '../images')))
Then where we r using images just type http ://domain/images/imageName然后我们在使用图像的地方只需输入 http://domain/images/imageName
Thank You谢谢你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.