[英]CORS issue in (Nodejs + Angular 6 + socket.io)
當我們嘗試連接到服務器時,我們在使用 socket.io 客戶端的 Angular 6 中面臨 CORS 問題。
我們在瀏覽器控制台中得到的錯誤。
Access to XMLHttpRequest at 'http://********.com/socket.io/?EIO=3&transport=polling&t=N3jTiAZ' from origin 'http://localhost:4200' has been blocked by CORS policy:
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
這是服務器代碼
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const server = require('http').createServer(app);
const conn = app.listen("3000")
const io = require('socket.io').listen(conn);
io.origins('*:*')
var connectioncheck = io.of('/check-connection');
connectioncheck.on('connection', function (socket) {
console.log('user connected');
});
這是使用簡單的 html 和 js 的前端代碼
<script src="https://cdn.jsdelivr.net/npm/socket.io-client@2/dist/socket.io.js"></script>
var socket = io.connect('http://********.com/check-connection');
socket.emit('connection', "hello",function(db){
console.log(db);
console.log("data from callback");
});
根據意見,你給上面,我認為你應該像一個方式使用NPM CORS 這
let allowedOrigins = ["http://ServerA:3000", "http://ServerB:3000"]
let origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.header("Access-Control-Allow-Origin", origin); // restrict it to the required domain
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.