javascript - Express+Socket.io 'Access-Control-Allow-Origin'问题,求帮忙

查看:82
本文介绍了javascript - Express+Socket.io 'Access-Control-Allow-Origin'问题,求帮忙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

1.后端socket.io配置

//app.js文件部分代码...
app.use(function (req, res, next) {
  const origin = req.headers.origin
  if (typeof origin === 'undefined') {
    // No Cross Origin redirect
    res.header('Access-Control-Allow-Origin', '*')
  } else if (
    (origin.indexOf('http://localhost')) === 0 ||
    (origin.indexOf('http://172.16.') === 0) ||
    (origin.indexOf('http://192.168.1.') === 0) ||
    (origin.indexOf('http://admin.anguer.com') === 0) ||
    (origin.indexOf('http://chat.anguer.com') === 0)
  ) {
    res.header('Access-Control-Allow-Origin', origin)
    res.header('Access-Control-Allow-Credentials', 'true')
  } else {
    res.header('Access-Control-Allow-Origin', 'http://localhost')
  }
  res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, X-Access-Token')

  next()
})

// bin/www
const app = require('../src/app')
const http = require('http')
app.set('port', 12345)
const server = http.createServer(app)

const _io = require('socket.io')(server)
_io.set('transports', ['websocket', 'xhr-polling', 'jsonp-polling', 'htmlfile', 'flashsocket']);
_io.set('origins', '*:*');
_io.of('/socket-server').on('connection', function (socket) {
  // do something...
})

2.前端连接

const socket = io('domain.com:12345')

3.错误信息

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

解决方案

解决方案:为socket.io 配置新的端口

const _io = require('socket.io')(server)
_io.listen(12312)

这篇关于javascript - Express+Socket.io 'Access-Control-Allow-Origin'问题,求帮忙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆