我正在尝试在我的react应用中实现身份验证,并且每当我尝试在部署时尝试发布到我的快速API路由之一时,都会收到404错误。如果有帮助,我正在部署的服务器就是AWS EC2。
这是我的Server.js文件:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const passport = require('passport');
const cors = require('cors');
const users = require('./routes/api/users');
const app = express();
app.use(cors());
// Bodyparser Middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// DB Config
const db = require('./config/keys').mongoURI;
// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true, useUnifiedTopology: true }
)
.then(() => console.log("MongoDB successfully connected"))
.catch(err => console.log(err));
// Passport middleware
app.use(passport.initialize());
// Passport config
require('./config/passport')(passport);
// Routes
app.use('/api/users', users)
// Serve static assets if in production
if (process.env.NODE_ENV === 'production') {
// Set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
我的./routes/api/users.js文件:
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const keys = require("../../config/keys");
// Load input validation
const validateRegisterInput = require("../../validation/register");
const validateLoginInput = require("../../validation/login");
// Load User model
const User = require("../../models/User");
// @route POST api/users/register
// @desc Register user
// @access Public
router.post("/register", (req, res) => {
// Form validation
const { errors, isValid } = validateRegisterInput(req.body);
// Check validation
if (!isValid) {
return res.status(400).json(errors);
}
User.findOne({ email: req.body.email }).then(user => {
if (user) {
return res.status(400).json({ email: "Email already exists" });
} else {
const newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
// Hash password before saving in database
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
});
}
});
});
// @route POST api/users/login
// @desc Login user and return JWT token
// @access Public
router.post("/login", (req, res) => {
// Form validation
const { errors, isValid } = validateLoginInput(req.body);
// Check validation
if (!isValid) {
return res.status(400).json(errors);
}
const email = req.body.email;
const password = req.body.password;
// Find user by email
User.findOne({ email }).then(user => {
// Check if user exists
if (!user) {
return res.status(404).json({ emailnotfound: "Email not found" });
}
// Check password
bcrypt.compare(password, user.password).then(isMatch => {
if (isMatch) {
// User matched
// Create JWT Payload
const payload = {
id: user.id,
name: user.name
};
// Sign token
jwt.sign(
payload,
keys.secretOrKey,
{
expiresIn: 31556926 // 1 year in seconds
},
(err, token) => {
res.json({
success: true,
token: "Bearer " + token
});
}
);
} else {
return res
.status(400)
.json({ passwordincorrect: "Password incorrect" });
}
});
});
});
module.exports = router;
以下是我对express api的调用之一的示例:
// Register User
export const registerUser = (userData, history) => dispatch => {
axios
.post("http://localhost:5000/api/users/register", userData)
.then(res => history.push("/login")) // re-direct to login on successful register
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
当我在部署到服务器时提交表单时,出现此错误:
POST https://domainname.net/api/users/register 404(未找到)
我的前端在端口3000上运行,我的api服务器在端口5000上运行。我的所有代码都在本地运行,并且我不知道在部署到ec2服务器时会发生什么情况。
答案 0 :(得分:0)
尝试一下:
export const registerUser = (userData, history) => dispatch => {
axios
.post("http://yourdomain:5000/api/users/register", userData)//change in url
.then(res => history.push("/login")) // re-direct to login on successful
register
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
在您的域之后,您需要提供服务器的端口号。因为默认情况下,POST https://domainname.net/api/users/register 404 (Not Found)
的端口号为80。所以这里什么也没有。
答案 1 :(得分:-1)
在您的应用程序package.json
文件中,添加以下行:
"proxy": "http://localhost:5000", // server port
,您的操作网址为:
axios.post("/api/users/register", userData)
因此,当您为react app运行生产版本时,它将位于client/build
文件夹中,并且您将为该文件夹提供静态服务。客户端和服务器将位于同一端口5000
因此/api/users/register
将被发送到运行端口5000的服务器