我用Vue.js编写了一个小型前端项目,而Express在后端被采用。前端和后端分别位于两个不同的目录中。该API在我的本地环境中有效,但是当我将后端api部署到Heroku并尝试由Postman进行GET请求时,它将无法正常工作。
在我的index.js
中:
这是侦听端口:
const port = process.env.PORT || 5000;
我正在使用猫鼬来连接mLab:
const db = require("./config/keys").mongoURI;
mongoose.connect(db)
我的package.json
在这里:
{
"name": "backend-api",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node index.js",
"server": "nodemon index.js"
},
"author": "Yeoman_Li",
"license": "ISC",
"devDependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.4",
"mongoose": "^5.4.0"
}
}
我的index.js
在这里:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
// CORS
app.all("*", (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
res.header(
"Access-Control-Allow-Headers",
"Content-type, Accept, X-Access-Token, X-Key"
);
if ("OPTIONS" == req.method) res.status(200).end();
else next();
});
const mediaReq = require("./routes/api/mediaReq");
// DB
const db = require("./config/keys").mongoURI;
// body-parser
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// connect to DB
mongoose
.connect(db)
.then(() => console.log("MonogoDB Connected"))
.catch(err => console.log(err));
// router
app.use("/api/mediaReq", mediaReq);
// port
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
这是我的api路由器:
const express = require("express");
const router = express.Router();
const mediaController = require("../../controllers/media");
// test
router.get("/test", (req, res) => {
res.json({ msg: "test works" });
});
// $route GET api/mediaReq/medias || /medias/:id
router.get("/medias", mediaController.allMedia);
router.get("/medias/:id", mediaController.byId);
router.post("/medias", mediaController.create);
router.delete("/medias/:id", mediaController.remove);
module.exports = router;
我用邮递员发送一个简单的GET请求,它可以工作:
http://localhost:5000/api/mediaReq/medias
但是当我尝试向我的heroku backend-api发送GET请求时,它不起作用:
https://fast-reaches-23458.herokuapp.com/api/mediaReq/medias