【问题标题】:Axios OAuth2 FastApiAxios OAuth2 FastApi
【发布时间】:2021-10-08 13:19:40
【问题描述】:

我真的不明白表单数据如何与 axios 一起工作。如何将变量传递给 axios?

这是我的代码:

  methods: {
login() {
  const username = this.username, password = this.password;

  axios.post(process.env.VUE_APP_LOGIN, {"username": username, "password": password})
  .then(response => {
    const {token, token_type} = response.data;
    console.log(token, token_type)
    // ['authorization'] = `Bearer ${token}`
    this.$store.commit('auth/SET_TOKEN', token)
  })

  },

和后端方法:

@router.post("/login", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"access_token": access_token, "token_type": "bearer"}

如何将变量传递给此 axios 以获取令牌?

【问题讨论】:

  • 很难说您实际上要求的是什么。您在调用 axios 时使用了变量——尽管是通过this。您是在问如何提取返回的令牌(您似乎已经在这样做),还是在问如何在从身份验证端点返回该令牌后将其包含在未来的请求中?
  • 我在问我认为我需要做用户名和密码的 pydantic 模型,然后我可以通过数据从 axios 获取它?

标签: javascript python oauth-2.0 axios fastapi


【解决方案1】:

好的,我找到了如何使用 form_data 输入用户名和密码的方法 JS 可以使用你需要的 formdata 类型来创建这样的 form_Data 列表

  const payload = new FormData()

然后在此处添加您需要的内容

payload.append(`name`, this.`variable`)

然后

axios.post(`link`, payload) {
   .then(response => {
   `get token`
})
}

【讨论】:

    【解决方案2】:
    const loginUser = async (e) => {
            e.preventDefault()
    
            const url = "http://127.0.0.1:8000/login/"
    
            setLoading(true)
    
            const username = logininfo.username
            const password = logininfo.password
    
    
            // we have to use formData cause we are expecting OAuth2PasswordRequestForm
            // in the backend
            const form_data = new FormData()
    
            form_data.append("username", username)
            form_data.append("password", password)
    
            axios.post(url, form_data).then((response) => {
                if (response.status === 200) {
                    swal("Registration Successful, you can now login")
                    navigate("/sign-up")
                }else {
                    swal("Registration Failed, please try again")
                    navigate("/sign-up")
                }
            }).catch((error) => {
                console.log(error)
            })
    
            setlogininfo({
                password: ""
            })
    
            // optional
            // setLoading(false)
        }
    

    这是因为您在后端期待 OAuth2PasswordRequestForm。这将通过创建 FormData 对象来解决您的问题。

    【讨论】:

      猜你喜欢
      • 2021-02-24
      • 2022-08-15
      • 1970-01-01
      • 2022-07-24
      • 2022-07-24
      • 2021-12-23
      • 2021-07-18
      • 1970-01-01
      • 2021-03-24
      相关资源
      最近更新 更多