嗨,我正在尝试在Express中创建API,但不确定在Express中如何使用此var user = client.fetchUser(req.params.userId).catch(res.send('<pre>500 internal server error</pre>'))
,它只会返回此错误:
(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.log(`App listening on port ${port}!`))
有没有办法解决这个问题。
谢谢恩德
答案 0 :(得分:0)
我认为您发送两次重新发送。一次出错,之后一次。因为您总是发送第二行。要么等待并检查值,要么更好,那就是在如下所示的承诺中全部完成
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))
})
我在这里未经测试就编写了这段代码。