如何将PHP Curl命令转换为Axios POST请求
将PHP Curl POST请求转换为Axios
先逐个对应Curl参数与Axios配置项:
CURLOPT_URL: 对应Axios配置的url字段CURLOPT_HEADER: false: Axios默认不会将响应头混入响应体,直接取response.data即可获取返回内容CURLOPT_POST: true: 对应Axios的method: 'post'CURLOPT_POSTFIELDS: "some string": 该字符串为表单格式,需设置请求头Content-Type: application/x-www-form-urlencoded,并将字符串作为data传入CURLOPT_FRESH_CONNECT: true: 强制不重用连接,Node.js环境需配置http.Agent禁用keep-alive;浏览器环境无直接对应项,一般无需额外处理CURLOPT_FOLLOWLOCATION: false: 对应Axios的maxRedirects: 0,禁止跟随重定向CURLOPT_CONNECTTIMEOUT: 0: 设置请求无超时限制,对应Axios的timeout: 0CURLOPT_RETURNTRANSFER: true: Axios默认返回响应数据,无需额外配置
浏览器环境Axios代码
axios({ url: 'https://www.test.com', method: 'post', data: 'some string', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, maxRedirects: 0, timeout: 0 }) .then(response => { const returned_info = response.data; // 处理返回数据 }) .catch(error => { // 处理错误 });
Node.js环境Axios代码
(需额外配置Agent禁用keep-alive以匹配CURLOPT_FRESH_CONNECT: true)
const axios = require('axios'); const http = require('http'); const https = require('https'); // 创建禁用keep-alive的Agent实例 const httpAgent = new http.Agent({ keepAlive: false }); const httpsAgent = new https.Agent({ keepAlive: false }); axios({ url: 'https://www.test.com', method: 'post', data: 'some string', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, maxRedirects: 0, timeout: 0, httpAgent, httpsAgent }) .then(response => { const returned_info = response.data; // 处理返回数据 }) .catch(error => { // 处理错误 });
补充说明
如果你的some string是键值对格式(比如key1=value1&key2=value2),也可以用URLSearchParams构建数据,Axios会自动设置正确的Content-Type:
const params = new URLSearchParams(); params.append('key1', 'value1'); // 添加更多参数... axios({ url: 'https://www.test.com', method: 'post', data: params, maxRedirects: 0, timeout: 0 // Node.js环境需添加Agent配置 })
内容的提问来源于stack exchange,提问作者Chris Hunter-Johnson
相关产品推荐
相关产品推荐

