Javascript 为什么此节点应用程序在保存到MongoDB时挂起?
这些代码在本地工作得很好,有数据保存到MongoDB,我可以从中提取数据。但是,当它部署到Heroku时,应用程序挂起在“.save()”部分。不用说,MongoDB没有保存任何内容 我做错什么了吗?可能是.env部分吗? (也适用于repl.it和glitch,但不适用于Visual Studio代码的本地) 如果有人想看一眼,请查看完整代码 urlshortener.htmlJavascript 为什么此节点应用程序在保存到MongoDB时挂起?,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,这些代码在本地工作得很好,有数据保存到MongoDB,我可以从中提取数据。但是,当它部署到Heroku时,应用程序挂起在“.save()”部分。不用说,MongoDB没有保存任何内容 我做错什么了吗?可能是.env部分吗? (也适用于repl.it和glitch,但不适用于Visual Studio代码的本地) 如果有人想看一眼,请查看完整代码 urlshortener.html <form action="api/shorturl/new" method=&q
<form action="api/shorturl/new" method="POST">
<label for="url_input">URL to be shortened</label>
<input id="url_input" type="text" name="url" value="https://www.freecodecamp.org">
<input type="submit" value="POST URL">
</form>
server.js
// init project
require('dotenv').config();
var express = require('express');
var mongodb = require('mongodb');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var shortid = require('shortid');
var app = express();
var port = process.env.PORT || 3000
let uri = process.env.MONGODB_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
var cors = require('cors');
app.use(cors({ optionsSuccessStatus: 200 })); // some legacy browsers choke on 204
// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));
// http://expressjs.com/en/starter/basic-routing.html
app.get("/", function (req, res) {
res.sendFile(__dirname + '/views/index.html');
});
app.get("/urlshortener", function (req, res) {
res.sendFile(__dirname + '/views/urlshortener.html');
});
// testing API endpoint...
app.get("/api/hello", function (req, res) {
res.json({ greeting: 'hello API' });
});
// URL Shortener Microservice
// define the schema and build a model to store saved urls
let ShortUrl = mongoose.model('HerokuUrl', new mongoose.Schema({
original_url: String,
short_url: String,
suffix: String
}));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.post("/api/shorturl/new", (req, res) => {
let client_requested_url = req.body.url; // from input box
let suffix = shortid.generate(); // automatically generated
// this works
// res.json({
// 1: client_requested_url,
// 2: suffix
// })
let newUrl = new ShortUrl({
original_url: client_requested_url,
// short_url: client_requested_url + "/api/shorturl/" + suffix,
short_url: __dirname + "/api/shorturl/" + suffix,
suffix: suffix // suffix: suffix
})
// this works
// res.json({
// 'info': newUrl
// })
// APP HANGS at this save
newUrl.save((err, doc) => {
if (err) return console.error(err);
res.json({
original_url: newUrl.original_url,
short_url: newUrl.short_url,
suffix: newUrl.suffix // suffix: suffix
});
});
});
app.get("/api/shorturl/:suffix", (req, res) => {
let urlSuffix = req.params.suffix;
ShortUrl.findOne({ suffix: urlSuffix }).then(foundUrl => {
res.redirect(foundUrl.original_url);
});
})
// listen for requests
var listener = app.listen(port, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
尝试将mongo db atlas用于网络存储我已经可以使用了。。。 应用程序挂起在.save()上,因此它与数据库有关。 它在本地工作,但在我推到heroku时不工作,所以它与环境变量有关 我键入了heroku logs--tail,并记录了未定义的环境变量,如下所示:
UnhandledPromiseRejectionWarning: MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
因此,我四处窥探Stackoverflow,并将数据库uri作为配置变量添加到Heroku中。
成功了
谢谢大家。点击
/api/shorturl/new
api时,服务器控制台中是否有一些错误日志?是,“加载资源失败:服务器响应状态为503(服务不可用)”,如果newUrl.save()
遇到错误,您的请求处理程序将记录err
,但由于在这种情况下返回时没有调用res.send
,因此每当遇到任何错误时,API都将挂起。您可以在不“返回”console.error(err)
(这会停止处理程序的执行)的情况下响应错误,然后找出您遇到的错误以及原因。我将代码更改为此,并在控制台中得到错误:“post503(服务不可用)”newUrl.save((err,doc)=>{if(err)console.log(err);res.send(“这行吗?”)});
UnhandledPromiseRejectionWarning: MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.