当我为我的Auth发布数据时,控制台抛出此错误** 500(内部服务器错误)**我认为问题是我的服务器,首先检查数据库和数据在集群中但数据在我的客户端不起作用。我知道这类问题通常是在服务器上。我已经找了好几个小时了,还是想不出来。
这是索引
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
import postRoutes from './routes/posts.js';
import userRoutes from './routes/users.js';
const app = express();
app.use(bodyParser.json({ limit: '30mb', extended: true }))
app.use(bodyParser.urlencoded({ limit: '30mb', extended: true }))
app.use(cors());
app.use('/posts', postRoutes);
app.use('/users', userRoutes);
const CONNECTION_URL = '**THIS_IS_MY_MONGO_DB;
const PORT = process.env.PORT|| 5000;
mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`)))
.catch((error) => console.log(`${error} did not connect`));
mongoose.set('useFindAndModify', false);
users.js路由
import express from 'express';
import { signin, signup } from '../controllers/user.js';
const router = express.Router();
router.post('/signin', signin);
router.post('/signup', signup);
export default router;
用户控制器
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import User from "../models/user.js";
export const signin = async (req, res) => {
const { email, password} = req.body;
try {
const existingUser = await User.findOne({ email });
if(!existingUser) return res.status(404).json({ message: "El usuaruio no existe."});
const isPasswordCorrect = await bcrypt.compare(password, existingUser.password);
if(!isPasswordCorrect) return res.status(400).json({ message: "Credenciales invalidas."});
const token = jwt.sing({ email: existingUser.email, id: existingUser._id }, 'test', { expiresIn: "1h" });
res.status(200).json({ result: existingUser, token});
} catch (error) {
res.status(500).json({ message: 'Algo salio mal.' });
}
}
export const signup = async (req, res) => {
const { email, password, confirmPassword, firstName, lastName } = req.body;
try {
const existingUser = await User.findOne({ email });
if(existingUser) return res.status(400).json({ message: "El usuaruio ya existe."});
if(password !== confirmPassword) return res.status(400).json({ message: "Las contraseñas no coinciden."});
const hashedPassword = await bcrypt.hash(password, 12);
const result = await User.create({ email, password: hashedPassword, name: `${firstName} ${lastName}` })
const token = jwt.sing({ email: result.email, id: result._id }, 'test', { expiresIn: "1h" });
res.status(200).json({ result, token});
} catch (error) {
res.status(500).json({ message: 'Algo salio mal.' });
}
}
索引api
import axios from 'axios';
const API = axios.create({ baseURL: 'http://localhost:5000' })
export const fetchPosts = () => API.get('/posts');
export const createPost = (newPost) => API.post('/posts', newPost);
export const likePost = (id) => API.patch(`/posts/${id}/likePost`);
export const updatePost = (id, updatedPost) => API.patch(`/posts/${id}`, updatedPost);
export const deletePost = (id) => API.delete(`/posts/${id}`);
export const signIn = (formData) => API.post('/users/signin', formData);
export const signUp = (formData) => API.post('/users/signup', formData);
export const signup = async (req, res) => {
const { email, password, confirmPassword, firstName, lastName } = req.body;
try {
const existingUser = await User.findOne({ email });
if(existingUser) return res.status(400).json({ message: "El usuaruio ya existe."});
if(password !== confirmPassword) return res.status(400).json({ message: "Las contraseñas no coinciden."});
const hashedPassword = await bcrypt.hash(password, 12);
const result = await User.create({ email, password: hashedPassword, name: `${firstName} ${lastName}` })
// you have typo in next line
const token = jwt.sing({ email: result.email, id: result._id }, 'test', { expiresIn: "1h" });
// replace it by:
const token = jwt.sign({ email: result.email, id: result._id }, 'test', { expiresIn: "1h" });
res.status(200).json({ result, token});
} catch (error) {
res.status(500).json({ message: 'Algo salio mal.' });
}
}