简体   繁体   English

axios post请求报错400是什么原因?

[英]What causes error 400 in axios post request?

I am writing a cli in oclif that consumes data from a rest api written in node.js.我正在 oclif 中编写一个 cli,它使用来自用 node.js 编写的 rest api 的数据。 I am trying to perform a post request that sends username and password, receives a token from the api and verifies it.我正在尝试执行发送用户名和密码的发布请求,从 api 接收令牌并验证它。

My code is the following in the file (Login.ts):我的代码在文件 (Login.ts) 中如下:

import Command from '@oclif/command'
import axios from 'axios'
import {flags} from  '@oclif/command'
const bcrypt = require('bcrypt');
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
export class LoginCommand extends Command {
  static flags = { 
    user: flags.string({dependsOn:['passw']}),
    //email: flags.string({dependsOn:['passw'],exlucsive:['user']}),
    passw: flags.string()
  }

  async run() {
        const {flags} = this.parse(LoginCommand); 
        var hash = bcrypt.hashSync(`${flags.passw}`,10);
        var fs=require('fs');
        var privateKey = fs.readFileSync('private.key');
        const token=await axios.post('https://localhost:8765/energy/api/Login?username=' +`${flags.user}` +'&passw=' + hash);
        jwt.verify(JSON.stringify(token),privateKey,function(err,decoded){
            fs.writeFileSync('softeng19bAPI.token',JSON.stringify(token));
        });

My code in the file (entry.routes.js):我在文件中的代码(entry.routes.js):

app.post("/energy/api/Login", function(req,res){ 
        var jwt=require('jsonwebtoken');
        var password,e,a,q,p;
        sql.query(`SELECT user,pass,quota,apikey,email FROM users WHERE user=?`,[req.query.username],(err,res1) => {
            console.log(res1);
            password=res1[0].pass;
            e=res1[0].email;
            a=res1[0].apikey;
            q=res1[0].quota;
            p=res1[0].privileges;
        });
        if(req.query.passw = password){
                var jwt=require('jsonwebtoken');
                var privateKey = fs.readFileSync('/home/vangelis/softeng/energy/private.key');
                var token = jwt.sign({user:req.query.user ,passw: req.query.passw,email: e, quota: q,apikey: a,privileges: p }, privateKey, { algorithm: 'RS256' });
                res.status(200).send(token);
            }
        else res.status(400).send("Bad Request");
  });
  }

I think this error is usually produced with axios post requests, but I can't find were the error occurs.我认为这个错误通常是由 axios post 请求产生的,但我找不到错误发生的原因。

Problem :问题

sql.query is callback type execution, meaning code-block with sql.query回调类型执行,意思是code-block with

if(req.query.passw = password)

would be executed before之前会被执行

password=res1[0].pass;

such as it is(presumably) asynchronous.例如它(大概)是异步的。

The problem of 400 (mentioned in comments to the post) is the usage of the assignment( = ) and not comparison( === ), so code inside if would be exactly like 400的问题(在帖子的评论中提到)是赋值( = )的使用而不是比较( === ),所以里面的代码if会完全一样

if(req.query.passw = undefined)

which is falsy , so a decision would move to else branch这是falsy ,所以决定将移至else分支

A Simple solution for this code:此代码的简单解决方案

move if-else inside callback of sql.querysql.query的回调中移动 if-else

PS falsy - assigning a value to a variable would return this value and in your case it is undefined ; PS falsy - 为变量赋值将返回该值,在您的情况下它是undefined的; to check this simply open Chrome's Console and execute 2 different cases:要检查这一点,只需打开 Chrome 的控制台并执行 2 种不同的情况:

var a = 1 // 1
var b = undefined // undefined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM