How can I add a custom HTTP header to ajax request with js or jQuery?

前端 未结 9 1119
独厮守ぢ
独厮守ぢ 2020-11-22 03:17

Does anyone know how to add or create a custom HTTP header using JavaScript or jQuery?

9条回答
  •  感情败类
    2020-11-22 03:56

    You can use js fetch

    async function send(url,data) {
      let r= await fetch(url, {
            method: "POST", 
            headers: {
              "My-header": "abc"  
            },
            body: JSON.stringify(data), 
      })
      return await r.json()
    }
    
    // Example usage
    
    let url='https://server.test-cors.org/server?enable=true&status=200&methods=POST&headers=my-header';
    
    async function run() 
    {
     let jsonObj = await send(url,{ some: 'testdata' });
     console.log(jsonObj[0].request.httpMethod + ' was send - open chrome console > network to see it');
    }
    
    run();

提交回复
热议问题