【问题标题】:I am getting 404 error and 204 error when consuming backend (node,vuejs)?使用后端(节点,vuejs)时出现 404 错误和 204 错误?
【发布时间】:2021-08-05 14:15:52
【问题描述】:

使用邮递员登录时,一切正常。但是当我做一个 axios 请求时,我得到 404 错误,并且直接在 204 错误之后。当我渲染我的 vue.js 页面时,我得到“无法获取 api/auth/signin。我还在某处收到一条消息,提示找不到用户。

我尝试过的: 前端:我尝试在我的 axios 请求中添加标头。我在控制台记录了数据,看起来非常好。

后端:更改了已弃用的正文解析器。

前端代码: 授权商店

import axios from "axios";

const state = {
  token: "",
  users: [],
};

const getters = {};

const actions = {
  async signIn(_, payload) {
    const response = await axios.post(
      "http://localhost:3000/api/auth/signin",
      { payload },

      {
        headers: {
          "Content-Type": "application/json",
        },
      }
    );

    console.log(response.data);
    console.log(response.headers);
    console.log(response.status);
  },
};

const mutations = {};

export default {
  state,
  getters,
  actions,
  mutations,
};

这是我的后端: 控制器

//signin
exports.signin = (req, res) => {
  User.findOne({
    username: req.body.username,
  })
    .populate("roles", "-__v")
    .exec((err, user) => {
      if (err) {
        res.status(500).send({ message: err });
        return;
      }

      if (!user) {
        return res.status(404).send({ message: "User Not found." });
      }

      var passwordIsValid = bcrypt.compareSync(
        req.body.password,
        user.password
      );

      if (!passwordIsValid) {
        return res.status(401).send({
          accessToken: null,
          message: "Invalid Password!",
        });
      }

      var token = jwt.sign({ id: user.id }, config.secret, {
        expiresIn: 86400, // 24 hours
      });

      var authorities = [];

      for (let i = 0; i < user.roles.length; i++) {
        authorities.push("ROLE_" + user.roles[i].name.toUpperCase());
      }
      res.status(200).send({
        id: user._id,
        username: user.username,
        email: user.email,
        roles: authorities,
        accessToken: token,
      });
    });
};

路线


module.exports = function (app) {
  app.use(function (req, res, next) {
    res.header(
      "Access-Control-Allow-Headers",
      "x-access-token, Origin, Content-Type, Accept"
    );
    next();
  });

  app.post(
    "/api/auth/signup",
    [
      verifySignUp.checkDuplicateUsernameOrEmail,
      verifySignUp.checkRolesExisted,
    ],
    controller.signup
  );

  app.post("/api/auth/signin", controller.signin);

还有我的服务器

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");
const Quote = require("./models/Quote");
const quoteRoute = require("./routes/quoteRoute");
const quoteController = require("../Maxico/controllers/quoteController");
const config = require("./config/config");
const verifySignup = require("./middlewares/verifySignUp");
const Role = require("./models/Role");

const app = express();
//Import routes
//const authRoute = require("./routes/auth");

var corsOptions = {
  origin: "http://localhost:8080/?#/",
};

app.use(cors(corsOptions));

app.use(express.urlencoded({ extended: true }));
app.use(express.json()); //

const db = require("./models/Quote");
mongoose
  .connect(
    "url",
    {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useFindAndModify: false,
    }
  )
  .then(() => {
    console.log("Connected to the database!");
  })
  .catch((err) => {
    console.log("Cannot connect to the database!", err);
    process.exit();
  });

app.use(express.json());
app.get("/", (req, res) => {
  res.send("Welcome to homepage");
});
app.use("/quote", quoteRoute);
require("./routes/authRoute")(app);
//require("./routes/userRoute")(app);

// initial roles

Role.estimatedDocumentCount((err, count) => {
  if (!err && count === 0) {
    new Role({
      name: "user",
    }).save((err) => {
      if (err) {
        console.log("error", err);
      }

      console.log("added 'user' to roles collection");
    });

    new Role({
      name: "moderator",
    }).save((err) => {
      if (err) {
        console.log("error", err);
      }

      console.log("added 'moderator' to roles collection");
    });

    new Role({
      name: "admin",
    }).save((err) => {
      if (err) {
        console.log("error", err);
      }

      console.log("added 'admin' to roles collection");
    });
    new Role({
      name: "superadmin",
    }).save((err) => {
      if (err) {
        console.log("error", err);
      }

      console.log("added 'superadmin' to roles collection");
    });
  }
});

// set port, listen for requests
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

【问题讨论】:

  • 如果你说邮递员没问题,那应该是cors问题。您可以尝试评论app.use(cors(corsOptions)); 并再次测试流程。如果可行,您能否尝试使用 origin http://localhost:8080 而不是 http://localhost:8080/?#/ 再次启用 cors
  • 我会试试的。我还想补充一点,相同的后端与另一个前端身份验证一起使用,前端请求之间的唯一区别是请求有效负载(网络选项卡)中的不同输出。 @MicFung
  • 那么可能是你 console.log 前端 signIn() 中的有效负载以查看是否包含用户名

标签: node.js vue.js express error-handling vuex


【解决方案1】:

在我的网络选项卡中,请求负载是这样发送的:

{payload: {username: "jon", password: "password"}}
payload: {username: "jon", password: "password"}

但我的邮递员只接受这个:

{username: "jon", password: "password"}

所以在我的操作中我是这样发送的:

const actions = {
  async signIn(_, payload) {
    console.log(payload);
    const response = await axios.post(
      "http://localhost:3000/api/auth/signin",
      payload,

      {
        headers: {
          "Content-Type": "application/json",
        },
      }
    );
    console.log(payload);
    console.log(response.data);
    console.log(response.headers);
    console.log(response.status);
  },
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-02
    • 2021-10-12
    • 1970-01-01
    • 2019-07-17
    • 2022-12-14
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多