NodeJS 网站只显示html而不是任何css或样式

4si2a6ki  于 2023-01-08  发布在  Node.js
关注(0)|答案(1)|浏览(171)

我使用react作为客户端,node.js作为服务器端,并使用webpack来传输。当我在本地主机上启动网站时,它丢失了所有的样式和css。有什么想法吗?这是我的前端webpack,用来处理我的前端代码的传输

const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  target: 'node',
  externals: [nodeExternals()],
  entry: './frontend/src/App',
  output: {
    path: path.resolve(__dirname, 'backend/build'),
    filename: 'bundle.js',
    libraryTarget: 'commonjs2',
    libraryExport: 'default'
  },
  module: {
    rules: [
      {
        test: /\.jsx$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react']
          }
        }
      },
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
          },
        ],
      },
      
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react']
          }
        }
      },
      
      {
        test: /\.css$/,
        use: [ 'css-loader'],
        sideEffects: true
      }
    ]
  }
};

这是处理服务器呈现的后端/server. js

const express = require('express');
const React = require('react');
const { renderToString } = require('react-dom/server');
const App = require('../backend/build/bundle');
const { matchPath } = require('react-router-dom');

const app = express();

// This is the middleware that will handle all routes
app.get('*', (req, res) => {
  // We create a context object that will be passed to the StaticRouter
  const context = {};

  // Render the app component to a string
  const html = renderToString(
    React.createElement(App, {
      location: req.url,
      context,
    })
  );

  // If the app component set a context.url value, it means the user
  // tried to access a protected route that they are not authenticated for.
  // In this case, we redirect them to the login page.
  if (context.url) {
    res.redirect(context.url);
  } else {
    // Send the rendered HTML as the response
    res.send(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>My App</title>
        </head>
        <body>
          <div id="root">${html}</div>
          <script src="/build/bundle.js"></script>
        </body>
      </html>
    `);
  }
});

app.listen(3000, () =\> {
console.log('Server is listening on port 3000');
});

这是我的前端App.js

import React from "react";
import { StaticRouter } from "react-router-dom/server";
import { Footer, Contact, WhoChawewo, Header } from "./containers";
import { Navbar, Background } from "./components";
import { Route, Routes } from "react-router-dom";
import "./App.css";

const App = (props) => {
  return (
    <StaticRouter location={props.location} context={props.context}>
      <Navbar />
      <Routes>
        <Route exact path="/" element={<Header />} />
        <Route path="/about" element={<WhoChawewo />} />
        <Route path="/contact" element={<Contact />} />
      </Routes>
      <Footer />
    </StaticRouter>
  );
};

export default App;

这是我的index.js

import React from 'react';
import ReactDom from 'react-dom';
import './index.css';
import App from './App';
ReactDom.render(
    <BrowserRouter>
      <App />
    </BrowserRouter>,
    document.getElementById('root')
  )

我试着添加样式加载器到前端的webpack配置中,但是我最终得到了一个错误,文档没有定义。路由工作正常,只是没有css或图像,只是呈现了基本的html。

2fjabf4q

2fjabf4q1#

查看HTML;您没有调用要加载的CSS。2请检查您的Web包为您生成的CSS文件,然后将其添加到HTML中。

  • 请注意,在这个HTML示例中,我添加了link标记 *
<!DOCTYPE html>
      <html>
        <head>
          <title>My App</title>
          <link href="/bundle/main.css" rel="stylesheet">
        </head>
        <body>
          <div id="root">${html}</div>
          <script src="/build/bundle.js"></script>
        </body>
      </html>
    • 2nd:**当您向Express服务器请求HTML时,必须发送它的JS和CSS文件。
const path = require("path");
const express = require('express');
const React = require('react');
const { renderToString } = require('react-dom/server');
const App = require('../backend/build/bundle');
const { matchPath } = require('react-router-dom');

const app = express();

app.use('/build', express.static(path.resolve(__dirname, "dist", "bundle")))

// This is the middleware that will handle all routes
app.get('/', (req, res) => {
  // We create a context object that will be passed to the StaticRouter
  const context = {};

  // Render the app component to a string
  const html = renderToString(
    React.createElement(App, {
      location: req.url,
      context,
    })
  );

  // If the app component set a context.url value, it means the user
  // tried to access a protected route that they are not authenticated for.
  // In this case, we redirect them to the login page.
  if (context.url) {
    res.redirect(context.url);
  } else {
    // Send the rendered HTML as the response
    res.send(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>My App</title>
          <link href="/main.css" rel="stylesheet">
        </head>
        <body>
          <div id="root">${html}</div>

          <script src="/build/bundle.js"></script>
        </body>
      </html>
    `);
  }
});

app.listen(3000, () => {
console.log('Server is listening on port 3000');
});

注:
请查看:应用程序. use('/build ',表达式. static(路径. resolve(__目录名,"dist","捆绑包"))
组织文件夹以指向实际的构建文件夹,请记住,这是一个示例

相关问题