In Apifox, use the postscript to display the base64 image in the response result response

background

When using Apifox to request an interface with pictures, I want to display pictures while the request is successful. At this time, I started to search for official documents on Baidu. Finally, it was found that the pictures in the response can be displayed using the post script.

plan

As shown in the figure below, after the interface request is successful, the returned JSON structure is:

{
    
    
	"images":[],
	"parameters":{
    
    },
	"info":""
}

insert image description here

1. Add postscript

At this point, I want to see the pictures in images after the request is successful, so how should I do it?
The answer is to use [custom postscript]. In the apxfox tool, find [Post-operation] -> [Add post-operation] -> [Custom script].
insert image description here

2. Add read code

Paste the following code into the tool, the parameters have been introduced in detail below, as follows:


//pm是apifox的内置对象,通过这个对象,可以获取到请求结果(response)
//通过.json()函数,获取到响应体中返回的json数据
let res = pm.response.json()

//定义一个模板,这个模板存的是
const template = `<html><img src="{
     
     {imgTemplate}}" /></html>`;

//构建img标签能识别的base64 url,注:如果接口返回的base64 url没有【data:image/png;base64,】则需要拼接进去,否则出不来图片。
//因接口返回的是一个数组,这里打印打一张图片
let img= "data:image/png;base64,"+ res.images[0];
//console.log(img) //打印

// 设置 visualizer 数据。
//template:模板,上面const定义的template。
// {imgTemplate: img},imgTemplate对应的是template中src的值;img指的是上述定义的img base64 url
pm.visualizer.set(template, {
    
    
    imgTemplate: img
})

insert image description here

3. Operation effect

After successfully requesting the interface, click [Visualize] to see the successfully displayed picture
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/qq_40600379/article/details/131142002