![](/img/trans.png)
[英]Socket.io - Origin not allowed by Access-Control-Allow-Origin
[英]No 'Access-Control-Allow-Origin' - Node / react / socket.io
我曾嘗試在我的項目中使用 socket.io 進行實時通知,但出現控制台錯誤,這是我的示例后端( nodejs
):
const express = require('express');
const app = express();
const Server = app.listen(1337);
const io = require('socket.io')(Server, {
origins: ["http://localhost:3000"],
handlePreflightRequest: (req, res) => {
res.writeHead(200, {
"Access-Control-Allow-Origin": "http://localhost:3000",
"Access-Control-Allow-Methods": "GET,POST",
"Access-Control-Allow-Headers": "my-custom-header",
"Access-Control-Allow-Credentials": true
});
res.end();
}
});
io.on('connection', (socket) => {
console.log('connected');
socket.on('message', (message) => {
console.log('message');
})
socket.emit('message', 'toto');
});
前端(Reactjs):
import './App.css';
import React, {useState, useEffect} from 'react';
import io from 'socket.io-client'
const socket = io('http://localhost:1337',{
withCredentials: true
})
function App() {
return (
<div className="App">
{/* <script src="http://localhost:1337/socket.io/socket.io.js"></script> */}
</div>
);
}
export default App;
這是我的導航器控制台上顯示的錯誤:
Access to XMLHttpRequest at 'http://localhost:1337/socket.io/?EIO=4&transport=polling&t=NVYt_fH' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
polling-xhr.js:202 GET http://localhost:1337/socket.io/?EIO=4&transport=polling&t=NVYuaDS net::ERR_FAILED
我無法弄清楚我的錯誤,我嘗試了太多解決方案,但沒有任何幫助/
感謝@Beerswiller 的關注,我發現我想念的是:
而不是使用:
const io = require('socket.io')(Server, {
origins: ["http://localhost:3000"],
handlePreflightRequest: (req, res) => {
res.writeHead(200, {
"Access-Control-Allow-Origin": "http://localhost:3000",
"Access-Control-Allow-Methods": "GET,POST",
"Access-Control-Allow-Headers": "my-custom-header",
"Access-Control-Allow-Credentials": true
});
res.end();
}
});
我改為:
const io = require('socket.io')(Server, {
cors: {
origin : "http://localhost:3000"
}
});
在前面部分我做:
const socket = io('http://localhost:1337')
代替:
const socket = io('http://localhost:1337',{
withCredentials: true
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.