2

I create a chrome extension in React. I am trying to download data via socket.io. I didn't get any errors, but the array is empty.

I should set the header and token, but I do not know where to do it in the app.js server. Where can I set:

const token = '12345'

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

How can I set port in server app.js and endpoint in client app.jsx if I create chrome extension?

Is there any other way (other than socket.io) to receive data in the method componentDidMount() in React without reloading the page?

When I go to the address http://127.0.0.1:4001, the console.log displays to me New client connected and Error: undefined

Server

//app.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;

Client

//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;
6
  • If it's a content script, Chrome no longer allows cross-origin requests there, see section 2 in the official CORB explainer. Commented Jul 4, 2019 at 10:32
  • In the react app you're creating a socket connection to https://b.application.com/api/v1/scores?expand=createdBy, shouldn't you be connecting to your own server app because your server app seems to make a request to this URL and send the response through the websocket. Commented Jul 6, 2019 at 14:28
  • @Titus So I have to change my endpoint in app.jsx client? Commented Jul 6, 2019 at 17:05
  • Can you explain the flow more? You want your chrome extension to connect to your socket io server and your server fetches data from endpoint and returns? Or you want your extension to directly pull data from endpoint? Commented Jul 6, 2019 at 19:19
  • @MunimMunna I retrieve the data in componentDidMount (), axios.get, url: https: //b.application.com/api/v1/scores? Expand = createdBy. I want to fetch data without reloading the page. I do not want to refresh the page every time. Commented Jul 6, 2019 at 19:30

3 Answers 3

6

I solved it:

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}`);
    }
  };
Sign up to request clarification or add additional context in comments.

Comments

4
+25
-----------Try Replacing app.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"; 
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});
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("https://b.application.com/api/v1/scores?expand=createdBy", {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                "Access-Control-Allow-Origin": "*",
                'token': token
            }
        }); // Getting the data from DarkSky
        console.log("res.data:- "+JSON.stringify(res.data,null,4));
        socket.emit("FromAPI", res.data);  // Emitting a new message. It wil be consumed by the client
    } catch (error) {
        console.error(`Error: ${error.code}`);
    }
};

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

11 Comments

In console I see only New client connected and Error: undefined
"b.application.com/api/v1/scores?expand=createdBy" you are trying to fetch data from correct api right?????
Yes. I fetch early dates in componentDidMount(), axios.get and was ok
replace error line with console.error("error:- ",error); and let me know what it prints
data: { error: 'Your request was made with invalid credentials.' } }, isAxiosError: true. Token is valid, because I use it in componentDidMount() and I normal fetch data
|
0

Try modifying app.jsx as:

import socketIOClient from "socket.io-client";

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            scores: [],
            receivedData:[],
            endpoint: "https://b.application.com/api/v1/scores?expand=createdBy",
            token: "12345"
        }
        this.onDataReceived = this.onDataReceived.bind(this);
        this.socket = socketIOClient(this.state.endpoint, {
            extraHeaders: {
                Authorization: `Bearer ${this.state.token}`
            }
        });
        this.socket.on("FromAPI", this.onDataReceived);
    }
    onDataReceived(receivedData) {
        console.log("receivedData ", receivedData);
        this.setState({
            receivedData: receivedData
        });
    }
        render() {
            return(
                <div></div>
            )
    }
}
export default App;

Try modifying app.js: function getApiAndEmit

replace the line: socket.emit("FromAPI", res.data);

io.emit("FromAPI", res.data);

3 Comments

what is the value of receivedData? can you please elaborate?
it's empty array
Where can I put token in app.js server?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.