javascript - Masalah 'Access-Control-Allow-Origin' Express+Socket.io, sila bantu
大家讲道理
大家讲道理 2017-06-20 10:06:19
0
1
1124

1. Konfigurasi soket.io bahagian belakang

//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. Sambungan bahagian hadapan

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

3.Mesej ralat

Tiada pengepala 'Access-Control-Allow-Origin' pada sumber yang diminta 'http://localhost:8080' tidak dibenarkan akses.

.
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

membalas semua(1)
曾经蜡笔没有小新

Isu merentas domain

const express = require('express');
const app = express();

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1');
    next();
});
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan