簡體   English   中英

嘗試發布到 api 路由時出現 404 錯誤

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

我正在嘗試在我的 React 應用程序中實施身份驗證,並且每當我在部署時嘗試 POST 到我的快速 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 上運行我的前端,在端口 5000 上運行我的 api 服務器。我的所有代碼都在本地運行,我不知道部署到我的 ec2 服務器時發生了什么。

嘗試這個:

 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。所以什么都不會存在。

在您的 react app package.json文件中添加以下行:

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

你的行動網址將是:

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

因此,當您為 react app 運行生產構建時,它將在client/build文件夾中,並且您靜態地為該文件夾提供服務。 客戶端和服務器將在同一個端口 5000

所以/api/users/register將被發送到運行端口 5000 的服務器

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM