Socket.io mime 不匹配错误

rel*_*der 3 javascript node.js socket.io

这是 app.js 文件

import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import http from 'http';
import event from 'events';
import io from 'socket.io';
import session from 'express-session';
import passport from 'passport';
import LocalStrategy from 'passport-local';
import multer from 'multer';
import fs from 'fs';
import passportLocalMongoose from 'passport-local-mongoose';
import postRoutes from './server/routes/posts.routes';
import commentRoutes from './server/routes/comments.routes';
import authRoutes from './server/routes/auth.routes';
import userRoutes from './server/routes/users.routes';
import {passportConfig} from './server/config/passport.config';
import {socketFunction} from './server/config/socket.io.config';
import path from 'path';

mongoose.connect('mongodb://localhost/blog');

const sanitizer = require('sanitize-html');
const app = express();

const server = http.Server(app);
const socket = io(server);
const localEvent = event.EventEmitter;
const myEvent = new localEvent();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,Access-Control-Allow-Origin, Content-Type, Accept, Authorization");
  res.header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");

  next();
 });


app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(session({
  secret: "some secret",
  resave: false,
  saveUninitialized: false
}))

passportConfig(app);

app.use(postRoutes);
app.use(commentRoutes);
app.use(authRoutes);
app.use(userRoutes);
app.use(express.static(path.join(__dirname, '/client')))
app.use(express.static(path.join(__dirname, 'node_modules')))
app.use(express.static(path.join(__dirname, 'uploads')))


const port = 6655;

['/admin/', '/admin/:var', '/admin/edit/:var'].forEach(function(url){
  app.get(url, (req, res)=>{
    res.sendFile(path.join(__dirname, '/client', '/dashboard', '/index.html'));
  })
})

const blogRoutes = ['/', '/articles', '/articles/:url', '/contact'];

blogRoutes.forEach(el=>{
  app.get(el, (req, res)=>{
    if(el === '/articles/:url'){
      socketFunction(socket, req.params.url, myEvent)
    }
    res.sendFile(path.join(__dirname, '/client', '/blog', '/blog.html')); 
  })
})

app.listen(process.env.PORT, process.env.IP, ()=>{
  console.log(`Express server listening on port ${process.env.PORT} and IP ${process.env.IP}`);
});
Run Code Online (Sandbox Code Playgroud)

这是我的socket.io.config文件

function socketFunction(io, url, event){
    const blog = io.of(`/articles/${url}`)
    const admin = io.of('/admin/home')
    blog.on('connection', (fromBlog)=>{
        console.log("Connection made on blog");
        fromBlog.on('comment', (msg)=>{
            event.emit('comment-posted', {
                msg: msg.message
            })
        })
    })
    admin.on('connection', (toAdmin)=>{
        console.log("Connection made on admin");        
        event.on('comment-posted', (msg)=>{
            toAdmin.emit('blog-comment', {
                msg: msg.message
            })
        })
    })
}

export {socketFunction}
Run Code Online (Sandbox Code Playgroud)

这是我的两个 html 文件

<!DOCTYPE html>
<html ng-app="blog">
  <head>
    <meta charset="utf-8">
    <base href="/blog" target="_blank">
    <title>Ayush Bahuguna | Web Developer</title>
    <link rel="stylesheet" href="/blog/dist/css/styles.css">
  </head>
  <body>
    <script src='/socket.io/socket.io.js' type="text/javascript" charset="utf-8"></script>
    <script src="/blog/dist/js/vendor.js" charset="utf-8"></script>
    <script src="/blog/dist/js/app.js" charset="utf-8"></script>
  </body>
</html>

<!DOCTYPE html>
<html ng-app="cms">
  <head>
    <meta charset="utf-8">
    <base href="/admin">
    <title>Blog Admin | Ayush Bahuguna</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
  </head>
  <body>
  <root></root>
  <script src="/socket.io/socket.io.js"></script>
  <script src="/dashboard/dist/plugins/tinymce/tinymce.min.js" charset="utf-8"></script>
  <script src="/dashboard/dist/js/vendor.js"></script>
  <script src="/angular-ui-tinymce/dist/tinymce.min.js" charset="utf-8"></script>
  <script src="/dashboard/dist/js/app.js"></script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我正在接收 The resource from “http://localhost:6655/socket.io/socket.io.js” was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

我检查了网络选项卡,socket.io.js文件上的类型设置为 text/html。我不知道为什么会发生这个问题,我没有任何路线。

我试图找到一种解决方法,通过使用socket.io 文件夹中的socket.io.js可用client文件,但事实证明 socket.io 不是在寻找该文件,而是在明确寻找/socket.io/socket.io.js

非常感激你的帮助。

rob*_*lep 9

问题是这样的:

const server = http.Server(app);
const socket = io(server);
...
app.listen(...);
Run Code Online (Sandbox Code Playgroud)

你应该打电话监听server...

server.listen(...);
Run Code Online (Sandbox Code Playgroud)

...或者让 Express 为您创建一个 HTTP 服务器(这是什么app.listen(),这也是它不工作的原因:当它创建一个新服务器时,该服务器没有socket.io附加到它):

const server = app.listen(...);
const socket = io(server);
Run Code Online (Sandbox Code Playgroud)

text/html您得到的响应可能是因为 404 响应。