Reputation: 99
Hi I'm trying to make a API in Express and I'm not sure how to use this var user = client.fetchUser(req.params.userId).catch(res.send('<pre>500 internal server error</pre>'))
inside Express, it just returns this error:
(node:33064) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:482:11)
at ServerResponse.header (M:\JS Bot\Outh\api\node_modules\express\lib\response.js:767:10)
at ServerResponse.contentType (M:\JS Bot\Outh\api\node_modules\express\lib\response.js:595:15)
at ServerResponse.send (M:\JS Bot\Outh\api\node_modules\express\lib\response.js:145:14)
at app.get (M:\JS Bot\Outh\api\app.js:20:9)
at Layer.handle [as handle_request] (M:\JS Bot\Outh\api\node_modules\express\lib\router\layer.js:95:5)
at next (M:\JS Bot\Outh\api\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (M:\JS Bot\Outh\api\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (M:\JS Bot\Outh\api\node_modules\express\lib\router\layer.js:95:5)
at M:\JS Bot\Outh\api\node_modules\express\lib\router\index.js:281:22
(node:33064) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:33064) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Code is below:
const express = require('express')
const { Client, RichEmbed } = require('discord.js');
const yt = require('ytdl-core');
const ffmpeg = require('ffmpeg');
const fs = require('fs');
const Discord = require('discord.js');
const ytapi = require('simple-youtube-api');
const app = express()
const port = 80
const client = new Discord.Client();
client.login("NTQwXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
app.get('/', async (req, res) => {
res.send('hi test')
})
app.get('/user/:userId', async (req, res) => {
var user = client.fetchUser(req.params.userId).catch(res.send('<pre>500 internal server error</pre>'))
res.send(`User grabbed was ${user}`).catch(console.error)
})
app.listen(port, () => console.log(`App listening on port ${port}!`))
Is there a way I can fix this.
Thanks, Ender
Upvotes: 2
Views: 8415
Reputation: 1798
I think you are sending res.send twice. once in the error and once right after. since you always send your second line. Either do await and check the value or better would be to do it all in the promise like below
app.get('/user/:userId', async (req, res) => {
client.fetchUser(req.params.userId)
.then(user => res.send(`User grabbed was ${user}`)
.catch(err => res.status(500).send(err))
})
I wrote this code here so untested.
Upvotes: 2