VueJS:axios 在 POST 请求中返回 404 Not Found 错误

时间:2020-12-22 01:57:54

标签: node.js vue.js post axios http-post

更新并覆盖以前的获取方法。现在使用 POST

这个问题似乎与另一个 Stackers 之前提出的问题相似。但我真的不知所措,几乎因为这个愚蠢的错误而筋疲力尽。当请求在页面加载时发送,它保持返回错误如下图所示:- POST Response

我很确定我可能在其他地方看错了,但是你们能帮我找出我没有注意到的错误在哪里吗?将在下面分享要使用的相关代码。准确地说,这是 VueJS。



查看页面

<template>
  <div class="container">
    <header class="jumbotron">
      <h3>{{ title }}</h3>
    </header>
    <div class="col-md-12">
      <div class="card card-container">
        <form name="form" @submit.prevent="handleBiodata">
          <div v-if="!successful">
            <div class="form-group">
              <label for="firstname">First Name</label>
              <input
                type="text"
                class="form-control"
                name="firstname"
                :value="firstname"
              />
            </div>

            <div class="form-group">
              <label for="lastname">Last Name</label>
              <input
                type="text"
                class="form-control"
                name="lastname"
                :value="lastname"
              />
            </div>

            <div class="form-group">
              <label for="age">Age</label>
              <input
                type="number"
                class="form-control"
                name="age"
                :value="age"
              />
            </div>

            <div class="form-group">
              <label for="address">Address</label>
              <input
                type="textarea"
                class="form-control"
                name="address"
                :value="address"
              />
            </div>

<p><strong>Response:</strong> {{ content }}</p>

            <div class="form-group">
              <button class="btn btn-primary btn-block">Save</button>
            </div>
          </div>
        </form>

        <div
        v-if="message"
        class="alert"
        :class="successful ? 'alert-success' : 'alert-danger'"
      >{{message}}</div>
      </div>
    </div>
  </div>
</template>

<script>
import {biodata} from '../modules/biodata.module';

export default {
  name: 'Biodata',
  data() {
    return {
      title: 'Biodata',
      submitted: false,
      successful: false,
      message: '',
      firstname: '',
      lastname: '',
      age: 30,
      address: '',
      uid: this.$store.state.auth.user.id,
      content: '',
      sent_info: ''
    };
  },
  computed: {
    currentUser() {
      return this.$store.state.auth.user;
    }
  },
  mounted() {
    biodata.getBiodata(this.$store.state.auth.user).then(//this is to get the user data from the backend
      response => {
        this.content = response.data.message;
      },
      error => {
        this.content =
          (error.response && error.response.data && error.response.data.message) ||
          error.message ||
          error.toString();
      }
    );
  }, 
  methods: {
    handleBiodata() {
      this.submitted = true;
      this.successful = true;
      this.message = 'Submitted!';
    }
  }
};
</script>

<style scoped>
label {
  display: block;
  margin-top: 10px;
}

.card-container.card {
  max-width: 350px !important;
  padding: 40px 40px;
}

.card {
  background-color: #f7f7f7;
  padding: 20px 25px 30px;
  margin: 0 auto 25px;
  margin-top: 50px;
  -moz-border-radius: 2px;
  -webkit-border-radius: 2px;
  border-radius: 2px;
  -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
  -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
  box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
}

.profile-img-card {
  width: 96px;
  height: 96px;
  margin: 0 auto 10px;
  display: block;
  -moz-border-radius: 50%;
  -webkit-border-radius: 50%;
  border-radius: 50%;
}
</style>


控制器

const db = require("../models");
const User = db.user_table;//user model
const { request } = require("express");

exports.infoBio = (req, res) => {
  res.status(200).send("Biodata Controller");
};

exports.getBio = (req, res, next) => {
  User.findByPk(req.body.request_body.user.id).then(user => {
  //User.findByPk(1).then(user => {
    if (!user) {
      return res.status(404).send({ message: "User Not found." });
    } else{
      res.status(200).send({ 
        message: user.username
      });
     }
  }).catch(err => {
    console.log(err);
    res.status(500).send({ message: err.message });
  });
};


模块

import axios from 'axios';
import {API_URL, authHeader, /*userState,*/ API_CALL_TIMEOUT} from './helper.module.js'

class Biodata {

  getInfoBio() {
    return axios.get(API_URL + '/biodata/infobio', { headers: authHeader() });
  }  

  getBiodata(user) {
    let auth_header = authHeader();
    let request_body = {
      'x-access-token':auth_header['x-access-token'],
      'user':user
    }
    return axios.post(API_URL + '/biodata/getbio', {request_body}, { timeout : API_CALL_TIMEOUT });
  }

}

export var biodata = new Biodata();

辅助模块

export const API_URL = 'http://localhost:8080';

export const API_CALL_TIMEOUT = 2000;// API call timeout in milliseconds

export function authHeader() {
    const user = JSON.parse(localStorage.getItem('user'));
    if (user && user.accessToken) {
        return {'x-access-token':user.accessToken};
    } else {
        return {};
    }
}

export function userState() {
    const user = JSON.parse(localStorage.getItem('user'));
    if(user){ 
        return {status:{loggedIn: true}, user};

    } else{ 
        return {status:{loggedIn: false}, user:null};
    }
}


控制台出错
Cannot POST /biodata/getbio

如果我对这个问题的最重要部分有误解,请提供帮助和建议。谢谢。

1 个答案:

答案 0 :(得分:0)

经过几个小时的尝试和错误尝试后,由于后端路由器文件的逻辑错误,我发现了这一点。这是代码:-

const authController = require("../controllers/auth.controller");
const bioController = require("../controllers/biodata.controller");

module.exports = function(app) {   
  app.use(function(req, res, next) {
    //allowing headers for CORS (Cross-origin resource sharing). 

    //this is to allow frontend and backend to communicate with eachother.

    //this is literally the first thing we check before we call "next()" method on express 
    //and continue with the rest of the routing checks.

    //SUPER IMPORTANT

    res.header(
      "Access-Control-Allow-Headers",
      "x-access-token, Origin, Content-Type, Accept"
    );
    next();
  });

  app.get(
    "/biodata/infobio",
    [authController.verifyToken],
    bioController.infoBio
  );

  app.post(
    "/biodata/getbio",
    [authController.verifyToken],
    bioController.getBio
  );   

};

根据此代码发现此问题后:-

<块引用>

app.post( "/biodata/getbio", [authController.verifyToken], bioController.getBio ); 我注意到我使用 app.get 而不是 app.post 导致我的请求返回错误 404(未找到)。我认为这个案例已经结束并向所有人道歉,因为我仍在学习 VueJS 和 axios。