Node.js 我对Heroku上的MEAN应用程序有问题。登录和注册。don';应用程序启动时不工作,但在postman上测试时工作
这是web请求服务.ts 我认为问题在于后端或前端的路由,因为它正在为邮递员工作。当我在本地启动服务器时,它也在heroku上工作,但是如果它不是在heroku上本地启动的,它只显示登录和注册的前端。它显示了“的问题”http://localhost:3000/api/users/login" 这是users.jsNode.js 我对Heroku上的MEAN应用程序有问题。登录和注册。don';应用程序启动时不工作,但在postman上测试时工作,node.js,angular,mongodb,heroku,Node.js,Angular,Mongodb,Heroku,这是web请求服务.ts 我认为问题在于后端或前端的路由,因为它正在为邮递员工作。当我在本地启动服务器时,它也在heroku上工作,但是如果它不是在heroku上本地启动的,它只显示登录和注册的前端。它显示了“的问题”http://localhost:3000/api/users/login" 这是users.js const express = require("express"); const router = express.Router(); const multer
const express = require("express");
const router = express.Router();
const multer = require("multer");
const Post = require("../db/models/post.model");
const jwt = require("jsonwebtoken");
const MIME_TYPE_MAP = {
"image/png": "png",
"image/jpeg": "jpeg",
"image/jpg": "jpg",
};
const { User } = require("../db/models/user.model");
// check whether the request has a valid JWT access token
let authenticate = (req, res, next) => {
let token = req.header("x-access-token");
jwt.verify(token, User.getJWTSecret(), (err, decoded) => {
if (err) {
res.status(401).send(err);
} else {
req.user_id = decoded._id;
next();
}
});
};
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const isValid = MIME_TYPE_MAP[file.mimetype];
let error = new Error("Invalid mime type");
if (isValid) {
error = null;
}
cb(error, "backend/images");
},
filename: (req, file, cb) => {
const name = file.originalname.toLowerCase().split(" ").join("-");
const ext = MIME_TYPE_MAP[file.mimetype];
cb(null, name + "-" + Date.now() + "." + ext);
},
});
router.post(
"",
[multer({ storage: storage }).single("image"), authenticate],
(req, res, next) => {
const url = req.protocol + "://" + req.get("host");
const post = new Post({
content: req.body.content,
username: req.body.username,
likesCount: 0,
liked: [],
comments: [],
imagePath: url + "/images/" + req.file.filename,
_userId: req.body._userId,
});
console.log(post);
post.save().then((result) => {
res.status(201).json({
message: "Post added succesfully!",
post: {
id: result._id,
userId: result._userId,
username: result.username,
content: result.content,
likesCount: 0,
liked: [],
comments: [],
imagePath: result.imagePath,
},
});
});
}
);
router.put("/:id", authenticate, (req, res, next) => {
const post = new Post({
_id: req.body.id,
content: req.body.content,
});
Post.updateOne({ _id: req.params.id }, post).then((result) => {
res.status(200).json({
message: "Update successful!",
});
});
});
router.get("/:id", (req, res, next) => {
Post.findById(req.params.id).then((post) => {
if (post) {
res.status(200).json(post);
} else {
res.status(404).json({
message: "Post not found!",
});
}
});
});
router.get("", (req, res, next) => {
Post.find().then((documents) => {
res.status(200).json({
message: "Posts fetched succesfully!",
posts: documents,
});
});
});
router.post("/like", (req, res, next) => {
console.log(req.body);
Post.find(
{
_id: req.body.postId,
},
{
likesCount: 1,
liked: {
$elemMatch: { $eq: req.body.userId },
},
}
).then((documents) => {
console.log(documents);
if (documents[0].liked.length == 0) {
Post.updateOne(
{
_id: req.body.postId,
},
{
$inc: { likesCount: 1 },
$push: { liked: req.body.userId },
}
).then((doc) => {
res.status(200).json({
message: "Like added succesfully!",
posts: doc,
newLikeCount: documents[0].likesCount + 1,
postId: documents[0]._id,
});
});
} else {
Post.updateOne(
{
_id: req.body.postId,
},
{
$inc: { likesCount: -1 },
$pull: { liked: req.body.userId },
}
).then((doc) => {
res.status(200).json({
message: "Like deleted succesfully!",
posts: doc,
newLikeCount: documents[0].likesCount - 1,
postId: documents[0]._id,
});
});
}
});
});
router.post("/addComment", (req, res, next) => {
Post.updateOne(
{
_id: req.body.postId,
},
{
$push: { comments: { username: req.body.username, text: req.body.text } },
}
).then((documents) => {
res.status(200).json({
message: "Comment added succesfully!",
postId: req.body.postId,
username: req.body.username,
text: req.body.text,
});
});
});
router.get("/user/:id", authenticate, (req, res, next) => {
Post.findByUserId(req.params.id).then((posts) => {
if (posts) {
res.status(200).json({
posts: posts,
});
} else {
res.status(404).json({
message: "Post not found!",
});
}
});
});
router.delete("/:id", authenticate, (req, res, next) => {
console.log(req.params.id);
Post.deleteOne({ _id: req.params.id }).then((result) => {
console.log(result);
res.status(200).json({ message: "Post deleted" });
});
});
module.exports = router;
这是login-component.ts。我应该改变所有的路线吗?因为问题出在localhost:3000上。它不应该显示localhost:3000,除非它留在代码中的某个地方,我找不到它
import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/app/auth.service';
import { HttpResponse } from '@angular/common/http';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-login-page',
templateUrl: './login-page.component.html',
styleUrls: ['./login-page.component.css'],
})
export class LoginPageComponent implements OnInit {
form: FormGroup;
constructor(private authService: AuthService, private router: Router) {}
ngOnInit() {
document.body.classList.add('background');
}
ngOnDestroy() {
document.body.className = "";
}
onLoginButtonClicked(email: string, password: string) {
console.log(email, password);
this.authService
.login(email, password)
.subscribe((res: HttpResponse<any>) => {
if (res.status === 200) {
// we have logged in successfully
this.router.navigate(['/']);
}
console.log(res);
});
}
}
控制台中的错误:
Package.json:
import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/app/auth.service';
import { HttpResponse } from '@angular/common/http';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-login-page',
templateUrl: './login-page.component.html',
styleUrls: ['./login-page.component.css'],
})
export class LoginPageComponent implements OnInit {
form: FormGroup;
constructor(private authService: AuthService, private router: Router) {}
ngOnInit() {
document.body.classList.add('background');
}
ngOnDestroy() {
document.body.className = "";
}
onLoginButtonClicked(email: string, password: string) {
console.log(email, password);
this.authService
.login(email, password)
.subscribe((res: HttpResponse<any>) => {
if (res.status === 200) {
// we have logged in successfully
this.router.navigate(['/']);
}
console.log(res);
});
}
}
require("dotenv").config();
const express = require("express");
const app = express();
const { mongoose } = require("./db/mongoose");
const bodyParser = require("body-parser");
const { Post } = require("./db/models/post.model");
const usersRoutes = require("./routes/users");
const postsRoutes = require("./routes/posts");
const path = require("path");
//const production = "https://sarajevotravel.herokuapp.com/";
//const development = 'http://localhost:3000/';
//const url = (process.env.NODE_ENV ? production : development);
if(process.env.NODE_ENV === 'production'){
//Set static folder
app.use(express.static('./client/dist'));
app.get('*', (req, res)=>{
res.sendFile(path.resolve(__dirname, 'client', 'dist', 'index.html'))
})
}
/* MIDDLEWARE */
//app.use(bodyParser.json());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use("/images", express.static(path.join("backend/images")));
// CORS HEADERS MIDDLEWARE
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Credentials", true);
res.header(
"Access-Control-Allow-Methods",
"GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE"
);
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, x-access-token, x-refresh-token, _id"
);
res.header(
"Access-Control-Expose-Headers",
"x-access-token, x-refresh-token"
);
next();
});
/* END MIDDLEWARE */
app.get('/ruta', (req,res)=>{
console.log('1')
res.send('Hi')
})
app.use("/api/users", usersRoutes);
app.use("/api/posts", postsRoutes);
module.exports = app;
app.listen(process.env.PORT || 3000, () => {
console.log("Server is listening on port 3000");
});