#axios #httprequest
Вопрос:
Я пытаюсь отправить запрос, axios
как показано ниже:
import * as vscode from "vscode";
import * as fs from "fs";
import * as path from "path";
import * as os from 'os';
import axios from 'axios';
import * as FormData from 'form-data';
/**
* Prefetch QRCode https://www.zhihu.com/api/v3/account/api/login/qrcode
* Get QRCode https://www.zhihu.com/api/v3/account/api/login/qrcode/${token}/image
* Query ScanInfo https://www.zhihu.com/api/v3/account/api/login/qrcode/${token}/scan_info
*/
const qrCodeUrl = "https://www.zhihu.com/api/v3/account/api/login/qrcode";
const uDIDUrl = 'https://www.zhihu.com/udid';
export class ZhihuService{
public async login(){
vscode.window.showInformationMessage("知乎登陆");
await this.qrcodeLogin();
}
protected async qrcodeLogin() {
var api = axios.create({
withCredentials: true
});
//pre-hand before get qrcode token
api.post(uDIDUrl, null,{
withCredentials:true
}).then(res =>{
console.log(api);
console.log(res.data);
}).catch(err =>{
console.log(err);
});
await api.post(qrCodeUrl, null,{
withCredentials:true
}).catch((error: any) =>{
console.log(error);
});
}
}
Ибо api.post(uDIDUrl
это возвращает ожидаемый результат.
Но для второго запроса он всегда возвращает 403, Если я проверю эти два URL-адреса reqeust в postman, он работает, проверяя ошибку во втором запросе, я мог видеть, что файлы cookie из ответа на первый запрос не были автоматически прикреплены.
Любое предложение будет оценено по достоинству.
Комментарии:
1. Вы пытались добавить
await
вapi.post(uDIDUrl
, как вы это сделалиawait api.post(qrCodeUrl
. Таким образом, теоретически он будет ждать ответа и получать файлы cookie, прежде чем вы вызовете второй запрос на публикацию.
Ответ №1:
Проблема здесь в том, что оба вызова API выполняются параллельно. Поскольку qrCodeUrl
зависит от uDIDUrl's
ответа, вам следует дождаться завершения первого вызова API.
Для этого у вас есть два варианта:
- Выполните
qrCodeUrl
вызов API внутри блока, а затемuDIDUrl
- Используйте ожидание в
uDIDUrl
запросе. (Предпочитайте это, потому что у вас уже есть асинхронная функцияqrcodeLogin
)
Кроме того, вам не нужно добавлять withCredentials
снова, так как вы написали это один раз при инициализации экземпляра axios.
import * as vscode from "vscode";
import * as fs from "fs";
import * as path from "path";
import * as os from 'os';
import axios from 'axios';
import * as FormData from 'form-data';
/**
* Prefetch QRCode https://www.zhihu.com/api/v3/account/api/login/qrcode
* Get QRCode https://www.zhihu.com/api/v3/account/api/login/qrcode/${token}/image
* Query ScanInfo https://www.zhihu.com/api/v3/account/api/login/qrcode/${token}/scan_info
*/
const qrCodeUrl = "https://www.zhihu.com/api/v3/account/api/login/qrcode";
const uDIDUrl = 'https://www.zhihu.com/udid';
export class ZhihuService {
public async login() {
vscode.window.showInformationMessage("知乎登陆");
await this.qrcodeLogin();
}
protected async qrcodeLogin() {
var api = axios.create({
withCredentials: true
});
//pre-hand before get qrcode token
await api.post(uDIDUrl).then(res => { // Added await here amp; removed extra parameters
console.log(api);
console.log(res.data);
}).catch(err => {
console.log(err);
});
await api.post(qrCodeUrl).catch((error: any) => {
console.log(error);
});
}
}
Комментарии:
1. Я пробовал кататься
await api.post(uDIDUrl)
на лодке илиawait api.post(uDIDUrl).then
сapi.post(qrCodeUrl)
, и то, и другое не работает.2. @Эдвард, не могли бы вы поделиться кодом, пожалуйста. Было бы легче ориентироваться и исправлять.
Ответ №2:
Мне кажется, что вам следует дождаться первого звонка, прежде чем делать второй. Либо await
на первом, либо выполните второе в then
предложении первого вызова, так как они зависят друг от друга.
// A Promise will be returned for POST uDIDUrl (never assigned anywhere) and execution will continue
api.post(uDIDUrl, null,{
withCredentials:true
}).then(res =>{
console.log(api);
console.log(res.data);
}).catch(err =>{
console.log(err);
});
// The execution will block until the returned Promise of the `POST qrCodeUrl` request is fulfilled
await api.post(qrCodeUrl, null,{
withCredentials:true
}).catch((error: any) =>{
console.log(error);
});
Комментарии:
1. Я пробовал boath await api.post(uDIDUrl) или await api.post(uDIDUrl).затем с api.post(qrCodeUrl) оба не работают.
Ответ №3:
Я думаю, что эти два запроса происходят одновременно, а не друг за другом.
Комментарии:
1. даже если я перенесу второй запрос на первый запрос, а затем заблокирую, он все равно будет ошибочным.