我尝试实现后端和前端应用程序,但即使我使用 cors,它也总是出现错误。
请帮忙验证一下下面的代码:
后端服务器.js
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIO(server);
const cors = require('cors');
const ds18b20 = require('ds18b20');
const port = 4001;
const getTemperature = require('./utils/temperature');
let interval;
io.on("connection", (socket) => {
console.log("New client connected");
if(interval) {
clearInterval(interval);
}
var sensorId = [];
ds18b20.sensors((err, id) => {
sensorId = id;
socket.emit('sensors', id);
});
setInterval(() => {
sensorId.forEach((id) => {
ds18b20.temperature(id, (err, value) => {
console.log(value);
socket.emit('FromAPI', {'id': id, 'value': value});
});
});
}, interval);
socket.on("disconnect", () => {
console.log("Client disconnected");
clearInterval(interval);
});
});
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.get('/', (req, res) => {
res.send('Hi');
});
server.listen(port, () => console.log(`Listening on port ${port}`));
来自 create-react-app 的前端 App.js
import React, { useState, useEffect } from 'react';
import socketIOClient from 'socket.io-client';
// import { Button, Input } from 'react-bootstrap';
const ENDPOINT = "http://172.20.10.5:4001";
const socket = socketIOClient(ENDPOINT);
function App() {
const [response, setResponse] = useState("");
useEffect(() => {
socket.on("FromAPI", data => {
setResponse(data);
})
}, [])
错误如下图所示:
[错误] Access-Control-Allow-Origin 不允许来源http://172.20.10.5:3000 。[错误] 由于访问控制检查, XMLHttpRequest 无法加载http://172.20.10.5:4001/socket.io/?EIO=4&transport=polling&t=NOu0oIM 。[错误] 无法加载资源: Access-Control-Allow-Origin 不允许Origin http://172.20.10.5:3000 。(socket.io,第 0 行)
慕沐林林
相关分类