我有一个用Laravel和vue.js编写的站点,也用nodejs。当我尝试使用http协议进入站点时,一切都很好,当我尝试进入https协议时,站点的一半没有加载,并且在控制台中我得到一个错误:
Access to XMLHttpRequest at 'https://example.com:8443/socket.io/?EIO=3&transport=polling&t=NPIJFIo' from origin 'https://example.com' has been blocked by CORS policy: No 'Access- Control-Allow-Origin 'header is present on the requested resource.
到https的重定向是在nginx本身上配置的,但我不能在NodeJS上这样做。我也不明白,如何正确添加ssl证书路径到我的app.js。
我的app.js:
const app = require('express')(),
server = require('https').createServer(app),
Redis = require('redis'),
RedisClient = Redis.createClient(),
io = require('socket.io')(server),
cors = require('cors'),
axios = require('axios');
const myArgs = process.argv.slice(2);
const domain = myArgs[0];
const SECRET_KEY = 'cZN^ZH8)mu~9e,>6M>3qKV=Ar^fFF,7/';
axios.defaults.baseURL = 'https://example.com/api/bot/';
server.listen(8081);
app.use(cors({
origin: true,
credentials: true
}));
我做错了什么?如果能得到帮助,我将不胜感激。
这是CORS问题,您需要为socket.io服务器添加CORS
选项。
参见处理SOCKET.IO的COR。
io = require('socket.io')(server, {
cors: {
origin: '*'
}
});