Node.js CORS请求未成功,webpack socket.io客户端
我正在mi客户端上使用带有Node.js CORS请求未成功,webpack socket.io客户端,node.js,express,webpack,socket.io,Node.js,Express,Webpack,Socket.io,我正在mi客户端上使用带有socket.io客户端(localhost:9000)的webpack,我正在尝试连接到服务器端socket.io(localhost:3001)server ///服务器端 const app = require("express")(); const http = require("http").createServer(app); const cors = require('cors'); app.use(cors({ origin: '*' })); app
socket.io客户端(localhost:9000)
的webpack,我正在尝试连接到服务器端socket.io(localhost:3001)
server
///服务器端
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')
})
})
Alway give me:已阻止跨源请求:同一源策略不允许读取远程资源。(原因:CORS请求未成功)您可以尝试通过
io.set('origins','*:*')设置socket.io的CORS指令吗?
并检查这是否会改变什么?@nasskalte.juni是的,我已经这样做了,对于记录,您可以使用设置标题的CORS库,然后在一行上添加标题。删除其中一个实现。