简体   繁体   English

尝试发布到 api 路由时出现 404 错误

[英]404 error when trying to post to api route

I am trying to implement authentication into my react app and I am recieving a 404 error whenever I try to POST to one of my express API routes while deployed.我正在尝试在我的 React 应用程序中实施身份验证,并且每当我在部署时尝试 POST 到我的快速 API 路由之一时,我都会收到 404 错误。 The server that I am deploying throus is AWS EC2 if it makes a difference.如果它有所不同,我正在部署的服务器是 AWS EC2。

Here is my Server.js file:这是我的 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}`));

My ./routes/api/users.js file:我的 ./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;

Here is an example of one of my calls made to the express api:这是我对 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
      })
    );
};

When I submit my form when I deploy to my server I get this error:当我在部署到服务器时提交表单时,出现此错误:

POST https://domainname.net/api/users/register 404 (Not Found) POST https://domainname.net/api/users/register 404(未找到)

I am running my front end on port 3000 and my api server on port 5000. All of my code works locally, and I have no idea what's happening when I deploy to my ec2 server.我在端口 3000 上运行我的前端,在端口 5000 上运行我的 api 服务器。我的所有代码都在本地运行,我不知道部署到我的 ec2 服务器时发生了什么。

Try this:尝试这个:

 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
   })
  );
};

After your domain,you need to give port number of your server.Because by default POST https://domainname.net/api/users/register 404 (Not Found) will take port number as 80.So nothing will be there.在您的域之后,您需要提供服务器的端口号。因为默认情况下POST https://domainname.net/api/users/register 404 (Not Found)会将端口号设为 80。所以什么都不会存在。

in your react app package.json file add below line :在您的 react app package.json文件中添加以下行:

 "proxy": "http://localhost:5000",  // server port 

and your url for action will be :你的行动网址将是:

 axios.post("/api/users/register", userData)

so when you run production build for react app , it will in client/build folder and you statically serve that folder .因此,当您为 react app 运行生产构建时,它将在client/build文件夹中,并且您静态地为该文件夹提供服务。 client and server will be on same port 5000客户端和服务器将在同一个端口 5000

so /api/users/register will be sent to server running port 5000所以/api/users/register将被发送到运行端口 5000 的服务器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM