I'm developing an app that fetches CHZZK liveChat and shows it in a browser screen.
I have to send POST request to /open/v1/sessions/events/subscribe/chat
for receive chat data from CHZZK server, but on browser, it returns a CORS error.
To solve my CORS problem, I tried to use proxy on express server, with createProxyMiddleware
, but it failed.
I tried to use Axios for proxy setting, but it returns same error,
Invaild CORS request
Here's my code - chat.js
:
// Subscribe CHZZK liveChat socket for receive chat data
const socketOption = {
reconnection: false,
'force new connection': true,
'connect timeout': 3000,
transports: ['websocket'],
};
const config = {
headers: {
'Client-Id': client_id,
'Client-Secret': client_secret,
'Content-Type': 'application/json',
}
};
axios.get(`http://localhost:8080/proxy/${baseURL}/open/v1/sessions/auth/client`, config)
.then(response => {
const sessionURL = response.data.content.url;
console.log(sessionURL)
const socket = io.connect(sessionURL, socketOption)
socket.on("SYSTEM", function (data) {
data = JSON.parse(data)
if (data.type == 'connected') {
let headers = {
'Authorization': `Bearer ${acTkn}`,
'Content-Type': 'application/json'
}
// server returns 'Invaild CORS request' below.
let url = `http://localhost:8080/proxy/${baseURL}/open/v1/sessions/events/subscribe/chat?sessionKey=${data.data.sessionKey}`
axios.post(url, {}, { headers: headers, withCredentials: true })
.then(response => {
getUserName()
.then(response => {
addOverlayChat(true, "[SYSTEM]", ` Connected to: ${response}`);
})
console.log(response.data);
})
.catch(error => {
console.error('Err:', error);
});
} else {
console.log(data)
}
});
main.js
:
const corsOptions = {
origin: 'http://localhost:8080',
credentials: true
};
server.use(cors(corsOptions));
server.use(express.json());
server.use(express.urlencoded({ extended: true }));
server.options('/proxy', cors(corsOptions));
server.use('/proxy', async (req, res) => {
const url = req.url.slice(1); // Remove the leading slash
const axiosConfig = {
method: req.method,
url: url,
headers: {
...req.headers,
host: undefined
}
};
if (req.method === 'POST') {
axiosConfig.data = req.body;
}
try {
const response = await axios(axiosConfig);
res.set('Access-Control-Allow-Origin', 'http://localhost:8080');
res.set('Access-Control-Allow-Headers', 'Authorization, Content-Type');
res.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.status(response.status).send(response.data);
} catch (error) {
console.error('Error:', error);
res.status(error.response ? error.response.status : 500).send('Internal Server Error');
}
});
How can I solve this problem? I spent about 6 hours but couldn't solve it yet
I've tried to use http-proxy
/ testing API response, /open/v1/sessions/events/subscribe/chat
works correctly / I want to avoid CORS policy in browser using proxy and receive chat data from /open/v1/sessions/events/subscribe/chat