简体   繁体   中英

How to solve cors error in socket.io laravel and nodejs signalling app

i have a chat app built with laravel and socket.io. My laravel app is located on one domain while my nodejs app is on another domain. Connecting to my nodejs signalling app gives a cors error while the nodejs app also returns cors error. Here is my nodejs app

"use strict";

require('dotenv').config();

const express = require('express');
const app = express();
const fs = require('fs');
const options = {
        key: fs.readFileSync(process.env.KEY_PATH),
        cert: fs.readFileSync(process.env.CERT_PATH)
    };
const https = require('https').Server(options, app);
const io = require('socket.io')(https);
io.origins('*:*');
const listner = https.listen(process.env.PORT, function() {
    console.log('Listening on ', listner.address().port);
});

//allow only the specified domain to connect
io.set('origins', process.env.DOMAIN + ':*');

require('./socket')(io);

app.get('/', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   // Add this
   if (req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, OPTIONS');
        res.header('Access-Control-Max-Age', 120);
        return res.status(200).json({});
    }
    res.send('Ok');
  
    next();

I have installed a cors middleware on my laravel backend but no difference whatsover. Any help will be appreciated

You need to remove these two line. cos, you have first set for any origin and the you have specified domain with env.

io.origins('*:*');
io.set('origins', process.env.DOMAIN + ':*');

Exact way to allow user is

// process.env.DOMAIN == "https://anydomain.com:port"
// process.env.DOMAIN != "anydomain.com:port"
const options={
 cors:true,
 origins:[process.env.DOMAIN],
}
const io = require('socket.io')(https, options);

Be sure the CORS configuration is setup correctly on your backend. Also note that sometimes the default settings of Apache or other environments may conflict with the settings you have applied.

The easiest way is you use the laravel-cors package

Another way is that you put this code in public/index.php file

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS, post, get');
header("Access-Control-Max-Age", "3600");
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Access-Control-Allow-Credentials", "true");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM