首页 > 解决方案 > Vuejs 在 axios 请求上抛出 400 (Bad Request) 错误

问题描述

我在端口 5000 上有 Nodejs,在端口 8080 上有 Vuejs。我使用的是 vue cli 3。首先我遇到了 CORS 问题,然后我通过添加 Koa-cors 模块解决了 CORS 问题。当我在 vuejs 中使用 koa restAPI 作为 POST 请求时。它抛出错误 400(错误请求)。为什么会来?发布请求是否存在语法问题?

API 响应

休息API

import * as Koa from "koa";
import * as Router from "koa-router";
import * as koaBody from "koa-body";
import * as cors from "@koa/cors";


  const app = new Koa();
  const router = new Router();
  const PORT = 5000;

  app.use(cors());
  app.use(koaBody({multipart: true}));

  app.use(router.routes()).use(router.allowedMethods());

      router.post('/api/admin_login', async (ctx: Koa.Context, next: () => Promise<any>) => {

        var email = ctx.request.body.email;
        var password = ctx.request.body.password;

        const checkEmailExist = await Admin.findOne({email: email});
            if (checkEmailExist != null) {

                const pwCorrect = await bcrypt.compare(password, checkEmailExist.password);
                if (pwCorrect === true) {
                    ctx.body = {
                        status: 200,
                        message: "Admin login successfully",
                        data: checkEmailExist,
                    };
                } else {
                    ctx.body = {
                        status: 400,
                        message: "Incorrect password",
                    }
                }
            } else {
                ctx.body = {
                    status: 400,
                    message: "Invalid Email",
                };

            }
        }
    });

Vuejs Axios 发布


 methods: {
            login() {
               const headers = {
                    'Content-Type': 'multipart/form-data; charset=UTF-8',
                    "Access-Control-Allow-Origin": "*",
                };

                this.$axios.post("http://localhost:5000/api/admin_login",
                    {
                        email: this.input.email,
                        password: this.input.password,
                    }, {
                        headers: headers
                    })
                    .then(response => {
                        console.log('data', data);
                    });
               }
        }

主.js

import Vue from "vue";
Vue.prototype.$axios = axios;

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");


标签: javascriptnode.jsvue.jsaxioskoa

解决方案


推荐阅读