我在端口5000上有Nodejs,在端口8080上有Vuejs。我使用的是vue cli3。首先,我遇到了CORS问题,然后我通过添加Koa-cors模块解决了CORS问题。当我在vuejs中使用koa restAPI作为POST请求时。它将引发错误400(错误请求)。为什么会来?发布请求是否存在语法问题?
RestAPI
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 Post
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);
});
}
}
Main.js
import Vue from "vue";
Vue.prototype.$axios = axios;
Vue.config.productionTip = false;
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");