我的expressJS应用程序遇到一些问题,发布到一条路由将始终导致Cannot set headers after they are sent to the client
-我不知道为什么和在何处两次发送请求/响应。
我尝试在函数中使用async
和await
来消除此错误,但最终总是回来。我也在写一个ID到数据库,我想这就是问题所在。但是我不这么认为,因为我基本上只是返回一个代码,甚至没有检查当前函数中的dynamodb.put
请求。
async function putNewUrl(inputUrl) {
const newId = await getId();
const short = ShortURL.encode(newId);
const params = {
TableName: URL_TABLE,
Item: {
long: inputUrl,
short,
},
};
try {
const data = await dynamoDb.put(params).promise();
return short;
} catch (error) {
console.log(error);
}
return short;
}
app.post('/submit', async (req, res) => {
const inputUrl = req.body.url;
try {
const shortUrl = await putNewUrl(inputUrl);
console.log(shortUrl)
return res.json({ success: true, message: shortUrl });
} catch(error) {
console.log(error)
return
}
});
这是我的进口货
import { config, DynamoDB } from 'aws-sdk';
import { json } from 'body-parser';
import express from 'express';
import helmet from 'helmet';
import { URL } from 'url';
const app = express();
app.use(helmet());
这是我启动服务器的方式
app.listen(3000, () => { console.log('app running'); });
解决了:
还有另一条这样的路线:
app.post('/submit', (req, res, next) => {
const inputUrl = req.body.url;
findExistingUrl(inputUrl, (error, data) => {
if (error) {
return res.json({ success: false, message: 'server error' });
}
if (typeof data.Items[0] === 'undefined' && data.Items[0] !== null) {
next();
} else {
return res.json({ success: true});
}
});
});
我又在最后一次打电话给next()
的地方。
答案 0 :(得分:0)
解决了它:
还有另一条这样的路线:
app.post('/submit', (req, res, next) => {
const inputUrl = req.body.url;
findExistingUrl(inputUrl, (error, data) => {
if (error) {
return res.json({ success: false, message: 'server error' });
}
if (typeof data.Items[0] === 'undefined' && data.Items[0] !== null) {
next();
} else {
return res.json({ success: true});
}
});
});
我再次在末尾调用next()的地方。