我正在使用Mern Stack作为后端。一切正常,直到我在“ auth.js”中键入“ signin”部分,但现在邮递员无法与本地主机连接。甚至我使用调试器来发现错误,但什么也没显示。我是erne的新手,因此无法弄清楚这里出了什么问题。我什至尝试关闭邮递员中的ssl认证。
邮递员屏幕截图:https://i.stack.imgur.com/BCrl8.png
VS代码屏幕截图:https://i.stack.imgur.com/WUxwz.png
以下是代码:
auth.js(路由)
var express = require('express');
var router = express.Router();
const { check, validationResult } = require('express-validator');
const {signout,signup, signin} = require("../controllers/auth");
router.post(
"/signup",
[
check("name","name should be atleast 3 char").isLength({ min: 3 }),
check("email","email is required").isEmail(),
check("password","password should be at least 3 char").isLength({min:3})
],signup);
router.post("/signin",[
check("email","email is required").isEmail(),
check("password","password field is required").isLength({min:3})
],signin);
router.get("/signout", signout);
module.exports = router;
auth.js(控制器)
const User = require("../models/user");
const { check, validationResult } = require("express-validator");
var jwt = require("jsonwebtoken");
var expressJwt = require("express-jwt");
exports.signup = (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({
error: errors.array()[0].msg
});
}
const user = new User(req.body);
user.save((err, user) => {
if (err) {
return res.status(400).json({
err: "NOT able to save user in DB"
});
}
res.json({
name: user.name,
email: user.email,
id: user._id
});
});
};
exports.signin = (req, res) => {
const errors = validationResult(req);
const { email, password } = req.body;
if (!errors.isEmpty()) {
return res.status(422).json({
error: errors.array()[0].msg
});
}
User.findOne({ email }, (err, user) => {
if (err || !user) {
return res.status(400).json({
error: "USER email does not exists"
});
}
if (!user.autheticate(password)) {
return res.status(401).json({
error: "Email and password do not match"
});
}
//create token
const token = jwt.sign({ _id: user._id }, process.env.SECRET);
//put token in cookie
res.cookie("token", token, { expire: new Date() + 9999 });
//send response to front end
const { _id, name, email, role } = user;
return res.json({ token, user: { _id, name, email, role } });
});
};
exports.signout = (req, res) => {
res.json({
message: "User signout"
});
};
app.js
require('dotenv').config();
const mongoose = require('mongoose');
const express = require("express")
const app = express();
const bodyParser = require ("body-parser");
const cookieParser = require ("cookie-parser");
const cors = require ("cors");
const authRoutes =require("./routes/auth");
// DB connection
mongoose.connect(process.env.DATABASE,{
useNewUrlParser:true,
useUnifiedTopology:true,
useCreateIndex:true
}).then(() => {
console.log("DB CONNECTED")
});
// Middlewares
app.use(bodyParser.json());
app.use(cookieParser());
app.use(cors());
// My Routes
app.use("/api", authRoutes);
//PORT
const port = process.env.PORT || 8000;
app. listen(port, () => {
console.log(`app is running at ${port}`);
} );
user.js
const mongoose = require ("mongoose");
const crypto = require('crypto');
const uuidv1 = require("uuid/v1");
var userSchema = new mongoose.Schema({
name: {
type: String,
required:true,
maxlength:32,
trim:true
},
lastname: {
type: String,
maxlength:32,
trim:true
},
email: {
type: String,
trim:true,
required:true,
unique:true
},
userinfo:{
type:String,
trim:true
},
encry_password:{
type:String,
required:true
},
salt: String,
role:{
type:Number,
default:0
},
purchases : {
type: Array,
default:[]
}
},{timestamps:true});
userSchema.virtual("password")
.set(function(password){
this._password= password;
this.salt = uuidv1();
this.encry_password = this.securePassword(password);
})
.get(function(){
return this._password
})
userSchema.methods = {
authenticate: function(plainpassword){
return this.securePassword(plainpassword)=== this.encry_password
},
securePassword: function(plainpassword){
if(!plainpassword) return "";
try{
return crypto
.createHmac('sha256', this.salt)
.update(plainpassword)
.digest('hex');
}catch(err){
return"";
}
}
};
module.exports = mongoose.model("User", userSchema );