Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 使用后端(节点,vuejs)时,我收到404错误和204错误?_Node.js_Vue.js_Express_Error Handling_Vuex - Fatal编程技术网

Node.js 使用后端(节点,vuejs)时,我收到404错误和204错误?

Node.js 使用后端(节点,vuejs)时,我收到404错误和204错误?,node.js,vue.js,express,error-handling,vuex,Node.js,Vue.js,Express,Error Handling,Vuex,当与邮递员登录时,一切正常。但当我执行axios请求时,我会得到404错误,并且直接在204错误之后。当我呈现我的vue.js页面时,我会看到“无法获取api/auth/sign。我还会在某个地方收到一条消息,说找不到用户” 我所尝试的: 前端:我尝试在axios请求中添加标题。我将数据记录在控制台中,看起来很好 后端:已更改不推荐使用的正文分析器 前端代码: 授权存储 import axios from "axios"; const state = { token:

当与邮递员登录时,一切正常。但当我执行axios请求时,我会得到404错误,并且直接在204错误之后。当我呈现我的vue.js页面时,我会看到“无法获取api/auth/sign。我还会在某个地方收到一条消息,说找不到用户”

我所尝试的: 前端:我尝试在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,
      });
    });
};

还有我的服务器

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


在“我的网络”选项卡中,请求付费负载按如下方式发送:

{payload: {username: "jon", password: "password"}}
payload: {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);
  },
};
但我的邮递员只接受这一点:

{username: "jon", password: "password"}
因此,在我的行动中,我发送了如下信息:

{payload: {username: "jon", password: "password"}}
payload: {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);
  },
};

如果你说邮递员没问题,那应该是cors的问题。你能试试注释
app.use(cors(corsOptions))吗
并再次测试该流。如果它有效,您是否可以尝试使用origin
再次启用corshttp://localhost:8080
而不是
http://localhost:8080/?#/
我会试试。我还想补充一点,同一个后端可以与另一个前端身份验证一起工作。前端请求之间的唯一区别是请求pa中的输出不同yload(网络选项卡)。@MicFungthen可能是您的控制台。将有效负载记录在前端
signIn()
中,查看是否包含用户名