gpt4 book ai didi

javascript - socket.io 连接返回一个空数组。在不重新加载页面的情况下在 React 中接收数据的方法?

转载 作者:搜寻专家 更新时间:2023-11-01 00:13:44 35 4
gpt4 key购买 nike

我在 React 中创建了一个 chrome 扩展。我正在尝试通过 socket.io 下载数据。我没有收到任何错误,但数组是空的。

我应该设置 header 和 token ,但我不知道在 app.js 服务器中的什么位置进行设置。在哪里可以设置:

const token = '12345'

headers: {
  'Authorization': `Bearer $ {token}`
}

如果我创建 ,如何在服务器 app.js 中设置 port 并在客户端 app.jsx 中设置端点Chrome 扩展程序?

有没有其他方法(除了 socket.io)可以在 ReactcomponentDidMount() 方法中接收数据而无需重新加载页面?

当我转到地址 http://127.0.0.1:4001 时,console.log 向我显示 New client connectedError: undefined

服务器

//应用程序.js

const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const axios = require("axios");
const port = process.env.PORT || 4001;/How port in `chrome extension?`
const index = require("./routes/index");
const app = express();
app.use(index);
const server = http.createServer(app);
const io = socketIo(server); // < Interesting!
const token = "12345";


let interval;
io.on("connection", socket => {
console.log("New client connected");
if (interval) {
clearInterval(interval);
}
interval = setInterval(() => getApiAndEmit(socket), 10000);
socket.on("disconnect", () => {
console.log("Client disconnected");
});
});

const getApiAndEmit = async socket => {
try {
const res = await axios.get(
"https://b.application.com/api/v1/scores?expand=createdBy"
); // Getting the data from DarkSky
socket.emit("FromAPI", res.data); // Emitting a new message. It will be consumed by the client
} catch (error) {
console.error(`Error: ${error.code}`);
}
};

server.listen(port, () => console.log(`Listening on port ${port}`));

//index.js

const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
res.send({ response: "I am alive" }).status(200);
});
module.exports = router;

客户端

//app.jsx

import socketIOClient from "socket.io-client";

class App extends Component {
constructor (props) {
super(props);
this.state = {
scores: []
endpoint: "http://127.0.0.1:4001" /How endpoint in `chrome extension`?
}
}

componentDidMount() {
const { endpoint } = this.state;
const token = "12345";

const socket = socketIOClient(endpoint);

socket.on("FromAPI", data => this.setState({ todos: data }));
}


render () {
<div>
</div>
)
}
}

export default App;

最佳答案

我解决了:

const getApiAndEmit = async socket => {
try {
const res = await axios.get(
"https://b.application.com/api/v1/scores?expand=createdBy",
headers: {
Authorization: `Bearer ${token}`
}
);
socket.emit("FromAPI", res.data); // Emitting a new message. It will be consumed by the client
} catch (error) {
console.error(`Error: ${error.code}`);
}
};

关于javascript - socket.io 连接返回一个空数组。在不重新加载页面的情况下在 React 中接收数据的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56885562/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com