Привет, я пытаюсь создать API в Express, и я не знаю, как использовать этот var user = client.fetchUser(req.params.userId).catch(res.send('<pre>500 internal server error</pre>')) внутри Express, он просто возвращает эту ошибку:
(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.
Код ниже:
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.info(`App listening on port ${port}!`))
Есть ли способ исправить это.
Спасибо, Эндер



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Я думаю, что вы отправляете res.send дважды. один раз в ошибке и один раз сразу после. так как вы всегда отправляете свою вторую строку. Либо ждите и проверьте значение, либо лучше сделать все это в обещании, как показано ниже.
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))
})
Я написал этот код здесь так непроверенный.
твое право. Собирался сделать оба варианта и забыл удалить.
Пользователь var все еще там, и теперь его обещание разрешается в undefined.
Либо используйте
await, либоthen(). В этом случае вам не нуженvar user = await, потому что пользователь никогда не используется, и если вы попытаетесь, это будет возвращаемое значениеres.send()илиres.status().send(), в зависимости от того, был ли выполнен catch.