我最近正在做一个小型的URL缩短程序,并且在本地运行良好,但是当我尝试将其部署到Heroku时,它给了我H12,请求超时错误,有人可以帮我找到我混乱的地方吗up。我的代码中包含异步函数,但我不知道哪个函数可能导致超时。
HTML
<div class="container">
<h1>URL Shrinker</h1>
<form action="/shortUrls" method="POST" class="my-4 form-inline">
<label for="fullUrl" class="sr-only">Url</label>
<input required placeholder="Url" type="url" name="fullUrl" id="fullUrl" class="form-control col mr-2">
<button class="btn btn-success" type="submit">Shrink</button>
</form>
<table class="table table-striped table-responsive">
<thead>
<tr>
<th>Full URL</th>
<th>Short Url</th>
<th>Clicks</th>
</tr>
</thead>
<tbody>
<% shortUrls.forEach(shortUrl => { %>
<tr>
<td><a href="<%= shortUrl.full %>"><%= shortUrl.full %></a></td>
<td><a href="<%= shortUrl.short %>"><%= shortUrl.short %></a></td>
<td><%= shortUrl.clicks %></td>
</tr>
<% }) %>
</tbody>
</table>
</div>
</body>
Server.js文件
const express = require('express');
const mongoose = require('mongoose');
const ShortUrl = require('./models/shortUrl');
const app = express();
mongoose.connect('mongodb://localhost/urlShortener', {
useNewUrlParser: true, useUnifiedTopology: true
})
app.set('view engine', 'ejs');
app.use(express.urlencoded({
extended: false
}))
app.get('/', async (req, res)=> {
const shortUrls = await ShortUrl.find()
res.render('index', { shortUrls: shortUrls});
});
app.post('/shortUrls', async(req, res)=>{
await ShortUrl.create({
full: req.body.fullUrl
})
res.redirect('/')
})
app.get('/:shortUrl', async(req, res)=>{
const shortUrl = await ShortUrl.findOne({ short: req.params.shortUrl })
if(shortUrl == null) return res.sendStatus(404)
shortUrl.clicks++
shortUrl.save()
res.redirect(shortUrl.full)
})
const port = process.env.PORT || 5000
app.listen(port, () => {
console.log(`server running at ${port}`)
});
答案 0 :(得分:0)
看起来您正在保存并在文档保存之前发送重定向(保存会返回承诺),在保存之前添加await
await shortUrl.save()