Error image 我认为前端没有与后端通信,但是由于我是MEAN新手,所以找不到问题。非常感谢您为解决该问题提供的帮助。
这是server.js文件。
const app = require("./backend/app");
const debug = require("debug")("node-angular");
const http = require("http");
const normalizePort = val => {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
};
const onError = error => {
if (error.syscall !== "listen") {
throw error;
}
const bind = typeof addr === "string" ? "pipe " + addr : "port " + port;
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
};
const onListening = () => {
const addr = server.address();
const bind = typeof addr === "string" ? "pipe " + addr : "port " + port;
debug("Listening on " + bind);
};
const port = normalizePort(process.env.PORT || "3000");
app.set("port", port);
const server = http.createServer(app);
server.on("error", onError);
server.on("listening", onListening);
server.listen(port);
这是app.js文件。
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const userRoutes = require('./routes/user');
const app = express();
mongoose.connect('mongodb://localhost:27017/shopping-cart')
.then(() =>{ console.log('Database connected');
}).catch(() => {
console.log('Connnection failed');
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cors());
app.use('/user', userRoutes);
module.exports = app;
服务提供商文件。
import { AuthData } from './auth-data.model';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({ providedIn: 'root'})
export class AuthService {
constructor(private http: HttpClient) {}
createUser(email: string, password: string) {
const authData: AuthData = { email: email, password: password };
this.http.post('http://localhost:3000/user/register', authData)
.subscribe(response => {
console.log(response);
});
}
}
用于创建用户的用户路线。
const express = require('express');
const User = require('../models/user');
const bcrypt = require('bcryptjs');
const router = express.Router();
router.post('/register'), (req, res, next) => {
bcrypt.hash(req.body.password, 10).then(hash => {
const user = new User({
email: req.body.email,
password: hash
});
user.save()
.then(result => {
res.status(201).json({
message: 'User Created',
result: result
});
})
.catch(err => {
res.status(500).json({
error: err
});
});
});
};
module.exports = router;
在注册新用户时,它应该创建一个新用户,但找不到404错误