我在mi客户端将Webpack与socket.io-client(localhost:9000)
一起使用,并且尝试连接到服务器端socket.io(localhost:3001)
服务器
///服务器端
const app = require("express")();
const http = require("http").createServer(app);
const cors = require('cors');
app.use(cors({ origin: '*' }));
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.header('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', false);
// Pass to next layer of middleware
next();
});
var path = require("path");
var cookieParser = require('cookie-parser');
app.use(cookieParser());
app.set('public', path.join(__dirname, 'public'));
const io = require('socket.io')(http,{
allowUpgrades: true,
transports: [ 'polling', 'websocket' ],
pingTimeout: 9000,
pingInterval: 3000,
cookie: 'mycookie',
httpCompression: true,
log: false,
agent: false,
origins: '*:*',
});
//io.set({ origins: 'localhost:9000'});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
http.listen(3001, function(){
console.log(`listening on ${3001}`);
});
我的客户端看起来像这样:
import _ from 'lodash';
import 'bootstrap';
import 'bootstrap/js/dist/util';
import 'bootstrap/js/dist/dropdown';
import Bootstrap from 'bootstrap/dist/css/bootstrap.css';
import '../styles/style.css';
import $ from 'jquery';
window.jQuery = $;
import io from 'socket.io-client';
var socket = io('https://localhost:3001');
//{transports: ['websocket', 'polling', 'flashsocket']}
socket.on('connect', () => {
// Get a list of all files, previously delete existing
// elements to avoid duplicates
console.log(socket.connected);
socket.on('file', (files) => {
console.log('Connected')
})
})
总是给我:跨域请求被阻止:同源策略禁止读取https://localhost:3001/socket.io/?EIO=3&transport=polling&t=MtbNn1m处的远程资源。 (原因:CORS请求未成功)