【问题标题】:How do i fill my parameter req.body with axios (Vue.js) to my Express.js server如何使用 axios (Vue.js) 将我的参数 req.body 填充到我的 Express.js 服务器
【发布时间】:2021-06-09 21:17:18
【问题描述】:

我正在尝试从我的 vue(我使用 vue.js)向我的 api 发送连接调用, 但是当我把对象req.body放在我的背上时,对象是空的

我读过这个:Axios post request.body is empty object 但这对我没有帮助

(它可以在 Postman 中使用,填充主体并带有 x-www-form-encoded 选项)

我从我的 Vue 得到这个: 我的 vue service.js

import Axios from 'axios';

class APIClient {
    constructor () {
        this.client = Axios.create({
            baseURL: 'http://localhost:8080'
        });
    }

    async connect () {

        const params = new URLSearchParams();
        params.append('mail', 'test');
        params.append('pwd', 'mypwd');
        return await this.client.get('/api/user/auth', params);

    }

我背了这个: index.ts:


import express from "express";
var cors = require('cors');
import "reflect-metadata";
var bodyParser = require('body-parser')

const http = require('http');
const MainRouter = require('./routes/main_router');

let port = 8080;
const server = express();

server.use(cors({origin: true}))
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({extended: true}))

let mainRouter = new MainRouter(server);

const httpServer = http.createServer(server);
httpServer.listen(port);
console.log('Server is listening');

和 main_router.ts


import express from 'express';
import mysql from "promise-mysql";

export default class MainRouter {

    public server: express.Express;
    
    constructor (server: express.Express) {
        super();
        this.server = server; 
        this.server.get("/api/user/auth", async (req: any, res: any) => {
            if (req.body) //the req.body is equal to {} instead of {mail: 'test', ...
                return res.json(await this.userManager.getUserByCredidentials(req.body));
            else return res.json([])
        });    
    }
}

module.exports = MainRouter;

我不知道我是否有东西要添加到我的快递服务器或我的带有 axios 的 vue 中?

【问题讨论】:

    标签: node.js vue.js express axios


    【解决方案1】:
    1. 您将 mailpwd 作为 GET 参数而不是在请求正文中传递。您可以使用req.query 访问,但是....
    2. 您应该避免使用 GET 将凭据作为 url 的参数发送,而是使用正文和 POST。如需更多信息,请参阅this post

    这是一个例子:

    return await this.client.post('/api/user/auth', {
       mail: "test",
       pwd: "mypwd"
    });
    

    当然别忘了把this.server.get("/api/user/auth",...改成this.server.post("/api/user/auth",...

    【讨论】:

    • 好的,谢谢你,成功了!我不会通过我的网址传递学分
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    相关资源
    最近更新 更多