我用mongodb在本地主机上运行正常,然后切换到mLab,这也很好,但是现在尝试再次在本地主机上运行数据库时,尝试连接时出现422错误。
GET http://localhost:3000/api/wines 422 (Unprocessable Entity)
我以前曾经部署过该站点,并且能够来回切换,所以不确定出什么问题。
这是我的server.js代码:
const express = require("express");
const path = require("path");
const PORT = process.env.PORT || 3001;
const app = express();
const mongoose = require("mongoose");
const routes = require("./routes");
// Connect to the Mongo DB
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/wineDB', { useNewUrlParser: true });
mongoose.connection.on("open", function (ref) {
console.log("Connected to mongo server.");
});
mongoose.connection.on('error', function (err) { console.log(err) });
// require("./models/wine");
// Define middleware here
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
// Add routes, both API and view
app.use(routes);
// Define API routes here
// Send every other request to the React app
// Define any API routes before this runs
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "./client/build/index.html"));
});
app.listen(PORT, () => {
console.log(` ==> API server now on port ${PORT}!`);
});
我想知道我的代码是否以某种方式尝试执行连接到mlab所需的生产模式,并且不再允许我通过本地主机连接到DB?
答案 0 :(得分:0)
实际上,我对来源有误。这是因为我的3001端口在后台运行,所以当我杀死它时,就解决了问题!