簡體   English   中英

Express NodeJS 路由錯誤文本/html 不是文本/事件流

[英]Express NodeJS Routing Error text/html is not text/event-stream

我有一個簡單的 Node Express 服務器設置,它提供一個帶有 bundle.js 的 html 文件。 每當我嘗試添加捕獲所有路由並重定向到主頁的路由時,當我打開一個未映射的路由時,我會在控制台中收到一條錯誤消息

“EventSource 的響應的 MIME 類型(“text/html”)不是“text/event-stream”。中止連接。”

我不確定這意味着什么,我在嘗試提供 index.html 時也遇到了問題(文件路徑的問題),所以這可能與此有關。 我正在嘗試在構建文件夾中提供 Index.html。

項目結構:
在此處輸入圖片說明

Index.js(服務器文件)

const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');

const app = express();
const server = http.createServer(app);

app.use(bodyParser.json());

app.use(express.static(path.join(__dirname, '.', 'public/build')));

app.get('/', (req, res) => {
    res.sendFile('index.html', {root: path.join(__dirname, 'public/build')});
    res.end();
});

app.all('*', (req, res) => {
    console.log('triggered');
    res.redirect('/');
    res.end();
});


server.listen(3000);

奇怪的是,當我轉到 localhost:3000 時,它會在節點控制台中打印“triggered”,如果我刪除捕獲任何其他路由的“app.all”代碼行,則它不再拋出此錯誤:

“EventSource 的響應的 MIME 類型(“text/html”)不是“text/event-stream”。中止連接。”

但是,如果刪除捕獲路由的代碼行,則會按預期收到錯誤“無法獲取 /routename”。

索引.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>project</title>
</head>

<body>
<div id="root"></div>
<script type="text/javascript" src="bundle.js"></script></body>

</html>

在 Index.html 文件中呈現的內容

import React from 'react';
import './styles/index.css';

const App = () => {
    return (
        <div>
            <h1>Home Page</h1>
            <button onClick={null}>Click Me</button>
        </div>
    );
};

export default App;

Index.js(客戶端)

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import App from './App';
import store from './redux/store';

require('webpack-hot-middleware/client');

ReactDOM.render(
    <Provider store={store}>
        <App/>
    </Provider>
    , document.getElementById('root')
);


我能夠通過擺脫 index.js(客戶端)文件中的 webpack 熱中間件導入語句來解決這個問題。

require('webpack-hot-middleware/client');

Webpack 中間件提供 EventStream 並期望 EventSource 的響應在 text/event-stream 上提供,並且由於文件通過 text/html 提供,因此會引發該錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM