Postman保存response的结果到本地文件中

1,280 阅读1分钟

如何把postman的response的结果保存到文件中

我使用中的postman版本为Version 10.12.0 (10.12.0),版本是比较新的。

保存文件的代码

需要在postman中的Tests中写下面的代码。


pm.sendRequest({
    url: 'http://localhost:3000/write',
    method: 'POST',
    
    header: {
        'Content-Type': 'application/json',
        'X-Foo': 'bar'
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({ data: pm.response.text(),fileName: pm.request.url })
    }
}, (err, res) => {
    console.log(res.json());
});

本地需要启动一个nodejs对应的服务

const express = require('express'),
    app = express(),
    fs = require('fs'),
    shell = require('shelljs'),

    // Modify the folder path in which responses need to be stored
    folderPath = './Responses/',
    defaultFileExtension = 'json', // Change the default file extension
    bodyParser = require('body-parser'),
    DEFAULT_MODE = 'writeFile',
    path = require('path');

// Create the folder path in case it doesn't exist
shell.mkdir('-p', folderPath);

// Change the limits according to your response size
app.use(bodyParser.json({limit: '50mb', extended: true}));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));

app.get('/', (req, res) => res.send('Hello, I write data to file. Send them requests!'));

app.post('/write', (req, res) => {
    const { data,fileName } = req.body
    console.log(JSON.stringify(fileName))
    const date = new Date().getTime();
    const fileNamePath = fileName.path[2]
    fs.writeFileSync('/Users/Responses/'+fileNamePath+'.html', data, 'utf8');
    res.send('Success');
});

app.listen(3000, () => {
    console.log('ResponsesToFile App is listening now! Send them requests my way!');
    console.log(`Data is being stored at location: ${path.join(process.cwd(), folderPath)}`);
});

postman是必须在本地启动一个服务才可以,ChatGPT提示的都是用fs的模块,但是新版本的postman是不支持这种模式的。所以必须要在本地启动一个,然后服务去接受数据。数据就可以存储到对应的目录。

参考连接: