为了账号安全,请及时绑定邮箱和手机立即绑定

CORS 和 EXPRESS - [错误] Access-Control-Allow-Origin

CORS 和 EXPRESS - [错误] Access-Control-Allow-Origin

catspeake 2023-10-14 16:49:08
我尝试实现后端和前端应用程序,但即使我使用 cors,它也总是出现错误。请帮忙验证一下下面的代码:后端服务器.jsconst 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.jsimport 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 行)
查看完整描述

1 回答

?
慕沐林林

TA贡献2016条经验 获得超9个赞

使用cors选项。

const io = socketIO(server, {

  cors: {

    origin: "*"

  }

})


查看完整回答
反对 回复 2023-10-14
  • 1 回答
  • 0 关注
  • 93 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信