1

I am getting this bizarre twilsoc error when trying to connect to twilio through node and react. I cannot figure out how to fix this. This seems to be happening on the server side of my application. I have generated the token based on the instructions on the website.

index.js:1437 Error: Can't connect to twilsock
        at Upstream.send (upstream.js:245)
        at TwilsockClient.post (client.js:280)
        at network.js:176
        at Retrier.<anonymous> (network.js:114)
        at Retrier.emit (events.js:136)
        at Retrier.attempt (retrier.js:56)
        at retrier.js:111

Here is on the front end

    componentDidMount() {
    fetch("http://localhost:3001/chat/token", {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded',
     'Access-Control-Allow-Origin': "*",
     'Access-Control-Allow-Headers': "*"
     },
      method: 'POST',
      body: `identity=${encodeURIComponent(this.props.username)}`
    })
      .then(res => res.json())
      .then(data => Chat.create(data.token))
      .then(this.setupChatClient)
      .catch(this.handleError);
  }

here is the server

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(pino);
app.use(cors());
const sendTokenResponse = (token, res) => {
  res.set('Content-Type', 'application/json');
  res.send(
    JSON.stringify({
      token: token.toJwt()
    })
  );
};

app.get('/api/greeting', (req, res) => {
  const name = req.query.name || 'World';
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify({ greeting: `Hello ${name}!` }));
});

app.get('/chat/token', (req, res) => {
  const identity = req.query.identity;
  const token = chatToken(identity, config);
  sendTokenResponse(token, res);
});

app.post('/chat/token', (req, res) => {
  console.log('this is firing on the backend')
  const identity = req.query.identity;
  const token = new AccessToken('AC821b3924fcf9577a0eb017c4b21b----', "SK8c95cf6ba0e4a0ec5499d12ae4d----", "o4x7JC9xTEAsZC06SVsnfb2xZU9n----");
  const chatGrant = new ChatGrant({
  serviceSid:"ISdd3f2b55594f45038ac88d84b78e----" ,
});
  token.addGrant(chatGrant);
  token.identity = identity;
  sendTokenResponse(token, res);
});

app.get('/video/token', (req, res) => {
  const identity = req.query.identity;
  const room = req.query.room;
  const token = videoToken(identity, room, config);
  sendTokenResponse(token, res);
});

app.post('/video/token', (req, res) => {
  const identity = req.body.identity;
  const room = req.body.room;
  const token = videoToken(identity, room, config);
  sendTokenResponse(token, res);
});

app.listen(3001, () =>
  console.log('Express server is running on localhost:3001')
);

5 Answers5

1

the latest versions of express are not using bodyparser.json any more, it's now a part of express, try using:

 express(express.json())

instead of

express(bodyParser.json())

OSEMA TOUATI
  • 327
  • 2
  • 13
1

Twilio developer evangelist here.

This actually looks like my code . This is good news, because it's from my post on how to proxy to an Express server with React so you can avoid CORS issues. If you are using my repo then you should be able to start both the server and the front end applications by running:

npm run dev

Then you don't need to fetch from an absolute URL, instead you can just use:

fetch("/chat/token", {
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  method: 'POST',
  body: `identity=${encodeURIComponent(this.props.username)}`
});

And the webpack dev server will proxy the request through to the Express application.

Let me know if that helps at all.

Quick note on CORS

I noticed you're trying to pass the headers 'Access-Control-Allow-Origin': "*", 'Access-Control-Allow-Headers': "*" from your fetch request. However they are not request headers, but response headers. If you do need CORS headers then you need your Express server to return them as part of the response.

But as I said, the way I set up the code for this post should mean that you don't need CORS at all. So you shouldn't have to worry about this for now.

philnash
  • 70,667
  • 10
  • 60
  • 88
  • Hey man!!! Nice to see you. Now I am getting this error: index.js:1437 Error: Can't connect to twilsock at Upstream.send (upstream.js:245) at TwilsockClient.post (client.js:280) at network.js:176 at Retrier. (network.js:114) at Retrier.emit (events.js:136) at Retrier.attempt (retrier.js:56) at retrier.js:111 – Alec Livinghouse May 27 '19 at 03:17
  • So this is in your client side, right? Do you have your api keys and chat service sid set up correctly on the server? Can you take one of the tokens that is generated and run it through https://jwt.io/ and see if it looks correct. – philnash May 27 '19 at 05:23
  • jwt.io says my token is invalid, you can see my server code above but I think the keys are set up correctly – Alec Livinghouse May 27 '19 at 13:10
  • Can you email me a token to philnash@twilio.com and I'll take a look. – philnash May 27 '19 at 14:02
0

If you're using express, the easiest way to achieve this is using the cors module.

First, install it using the next code:

npm install cors

Next, put the cors middleware in the express app:

app.use(cors())

If you want to learn more, read the cors module docs https://www.npmjs.com/package/cors

0

If none of these solutions work (they didn't for me), here's something that might be helpful which made the error go away for me: https://stackoverflow.com/a/56671780/404541

Bruno Bernardino
  • 476
  • 2
  • 5
  • 12
0

I had this problem because I mispelled the SIDs I was using when getting the token through the rest API. I made sure the SIDs were correct and the error went away.

halfer
  • 19,824
  • 17
  • 99
  • 186