TS/playwright - 如何使用x-www-form-urlencoded格式的请求体发送api请求?

6

我需要创建一个带有x-www-form-urlencoded格式的请求体的playwright API请求:

来自Postman的示例:

工作的postman请求示例

我试图这样做:

  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;

但是它没有起作用:/ 你能告诉我如何在playwright中编写这种请求吗?
2个回答

8

好的,我找到了一个解决方案!

 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;
        
    };


有关如何将此转换为Java的任何帮助吗? - undefined

0
我觉得你可以试试这个:
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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接