javascript TS/playwright -如何使用x-www-form-urlencoded体发布API请求?

nxowjjhe  于 2023-11-15  发布在  Java
关注(0)|答案(2)|浏览(134)

我需要用x-www-form-urlencoded body创建playwright API请求:来自postman的示例:working postman request example
我是这么说的:

async getNewApiAccesToken({request})
    {
        const postResponse = await request.post("https://login.microsoftonline.com//token",{
            ignoreHTTPSErrors: true,
            FormData: {
                'client_id': 'xyz',
                'client_secret': 'xyz',
                'grant_type': 'client_credentials',
                'scope': 'api://xyz'
            }
        })
        console.log(await postResponse.json());
        return postResponse;

字符串
但是它不起作用:/你能告诉我我怎么能写这样的要求在剧作家?

plicqrtu

plicqrtu1#

我找到解决办法了!

async getNewApiAccesToken({request})
    {
        const formData = new URLSearchParams();
        formData.append('grant_type', 'client_credentials');
        formData.append('client_secret', '8xyz');
        formData.append('client_id', 'xyz');
        formData.append('scope', 'api://xyz/.default');
        const postResponse = await request.post("https://login.microsoftonline.com/9xyz/v2.0/token",{
            ignoreHTTPSErrors: true,
            headers:{
                'Content-Type': 'application/x-www-form-urlencoded'
              },    
            data: formData.toString()  
        })
        return postResponse;
        
    };

字符串

nwsw7zdq

nwsw7zdq2#

我想你可以试试这个:

await request.post('https://login.microsoftonline.com/9xyz/v2.0/token', {
  headers:{
    'Content-Type': 'application/x-www-form-urlencoded'
  },  
  form: {
    grant_type: 'client_credentials',
    client_secret: '8xyz',
    client_id: 'xyz',
    scope: 'api://xyz/.default'
  }
});

字符串
根据文件:
“要将表单数据发送到服务器,请使用form选项。它的值将使用application/x-www-form-urlencoded编码编码到请求正文中”
https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-post

相关问题