title: Cross Origin Resource Sharing Error: missingalloworiginheader in socket.io tweets streamer app
body: <p>I have been working on a real-time tweet streamer app. Whenever the app tries to fetch new tweets, it throws up repeating errors in the console.</p>
  <p><a href="https://i.stack.imgur.com/7u19i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7u19i.png" alt="This error pops up multiple times in the console." /></a></p>
  <p>I looked into possible solutions and people suggested using the following code:</p>
  <pre><code>cors: {
      origin: &quot;*&quot;,
      methods: [&quot;GET&quot;, &quot;POST&quot;],
      allowedHeaders: [&quot;my-custom-header&quot;],
      credentials: true
    }
  </code></pre>
  <p>But this error led to another issue and now, my bearer token is not being authenticated.</p>
  <p><a href="https://i.stack.imgur.com/hcjXe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hcjXe.png" alt="enter image description here" /></a></p>
  <p>I am attaching the code of the server.js file below. Would really appreciate it if someone could help me understand the error and the solutions.</p>
  <pre><code>const express = require(&quot;express&quot;);
  const bodyParser = require(&quot;body-parser&quot;);
  const util = require(&quot;util&quot;);
  const request = require(&quot;request&quot;);
  const path = require(&quot;path&quot;);
  const socketIo = require(&quot;socket.io&quot;);
  const http = require(&quot;http&quot;);
  
  const app = express();
  let port = process.env.PORT || 3000;
  const post = util.promisify(request.post);
  const get = util.promisify(request.get);
  
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: true }));
  
  const server = http.createServer(app);
  const io = socketIo(server);
  
  
  const BEARER_TOKEN = process.env.TWITTER_BEARER_TOKEN;
  
  let timeout = 0;
  
  const streamURL = new URL(
    &quot;https://api.twitter.com/2/tweets/search/stream?tweet.fields=context_annotations&amp;expansions=author_id&quot;
  );
  
  const rulesURL = new URL(
    &quot;https://api.twitter.com/2/tweets/search/stream/rules&quot;
  );
  
  const errorMessage = {
    title: &quot;Please Wait&quot;,
    detail: &quot;Waiting for new Tweets to be posted...&quot;,
  };
  
  const authMessage = {
    title: &quot;Could not authenticate&quot;,
    details: [
      `Please make sure your bearer token is correct. 
        If using Glitch, remix this app and add it to the .env file`,
    ],
    type: &quot;https://developer.twitter.com/en/docs/authentication&quot;,
  };
  
  const sleep = async (delay) =&gt; {
    return new Promise((resolve) =&gt; setTimeout(() =&gt; resolve(true), delay));
  };
  
  app.get(&quot;/api/rules&quot;, async (req, res) =&gt; {
    if (!BEARER_TOKEN) {
      res.status(400).send(authMessage);
      return;
    }
  
    const token = BEARER_TOKEN;
    const requestConfig = {
      url: rulesURL,
      auth: {
        bearer: token,
      },
      json: true,
    };
  
    try {
      const response = await get(requestConfig);
  
      if (response.statusCode !== 200) {
        if (response.statusCode === 403) {
          res.status(403).send(response.body);
          return;
        } else {
          throw new Error(response.body.error.message);
        }
      }
  
      res.send(response);
      return;
    } catch (e) {
      res.send(e);
      return;
    }
  });
  
  app.post(&quot;/api/rules&quot;, async (req, res) =&gt; {
    if (!BEARER_TOKEN) {
      res.status(400).send(authMessage);
      return;
    }
  
    const token = BEARER_TOKEN;
    const requestConfig = {
      url: rulesURL,
      auth: {
        bearer: token,
      },
      json: req.body,
    };
  
    try {
      const response = await post(requestConfig);
  
      if (response.statusCode === 200 || response.statusCode === 201) {
        res.send(response);
        return;
      } else {
        throw new Error(response);
      }
    } catch (e) {
      res.send(e);
      return;
    }
  });
  
  const streamTweets = (socket, token) =&gt; {
    let stream;
  
    const config = {
      url: streamURL,
      auth: {
        bearer: token,
      },
      timeout: 31000,
    };
  
    try {
      const stream = request.get(config);
  
      stream
        .on(&quot;data&quot;, (data) =&gt; {
          try {
            const json = JSON.parse(data);
            if (json.connection_issue) {
              socket.emit(&quot;error&quot;, json);
              reconnect(stream, socket, token);
            } else {
              if (json.data) {
                socket.emit(&quot;tweet&quot;, json);
              } else {
                socket.emit(&quot;authError&quot;, json);
              }
            }
          } catch (e) {
            socket.emit(&quot;heartbeat&quot;);
          }
        })
        .on(&quot;error&quot;, (error) =&gt; {
          // Connection timed out
          socket.emit(&quot;error&quot;, errorMessage);
          reconnect(stream, socket, token);
        });
    } catch (e) {
      socket.emit(&quot;authError&quot;, authMessage);
    }
  };
  
  const reconnect = async (stream, socket, token) =&gt; {
    timeout++;
    stream.abort();
    await sleep(2 ** timeout * 1000);
    streamTweets(socket, token);
  };
  
  io.on(&quot;connection&quot;, async (socket) =&gt; {
    try {
      const token = BEARER_TOKEN;
      io.emit(&quot;connect&quot;, &quot;Client connected&quot;);
      const stream = streamTweets(io, token);
    } catch (e) {
      io.emit(&quot;authError&quot;, authMessage);
    }
  });
  
  console.log(&quot;NODE_ENV is&quot;, process.env.NODE_ENV);
  
  if (process.env.NODE_ENV === &quot;production&quot;) {
    app.use(express.static(path.join(__dirname, &quot;../build&quot;)));
    app.get(&quot;*&quot;, (request, res) =&gt; {
      res.sendFile(path.join(__dirname, &quot;../build&quot;, &quot;index.html&quot;));
    });
  } else {
    port = 3001;
  }
  
  server.listen(port, () =&gt; console.log(`Listening on port ${port}`));
  </code></pre>