如何将cURL请求转为等价Axios请求并解决CORS跨域报错
Axios等价实现Freshworks CRM接口请求及CORS问题解决方案
问题背景
执行以下cURL请求可正常获得接口响应,但自行编写的Axios代码触发CORS错误无法运行,需要实现完全等价的请求:
curl -H "Authorization: Token token=sfg999666t673t7t82" -H "Content-Type: application/json" -d '{"phone_call": { "call_direction": true, "targetable_type": "contact", "targetable": { "id": "1", "first_name": "Jane", "last_name": "Sampleton (sample)", "work_number ":"5304915427", "mobile_number ":"11919457004 " }, "note ": { "description": "Sample note"} }}' -X POST https://domain.myfreshworks.com/crm/sales/api/phone_calls
原有错误代码
const headers = { 'Content-Type': 'application/json', Authorization: 'Token sfg999666t673t7t82', }; var dataString = '{"phone_call": { "call_direction": true, "targetable_type": "contact", "targetable": { "id": "1", "first_name": "Jane", "last_name": "Sampleton (sample)", "work_number ":"5304915427", "mobile_number ":"11919457004 " }, "note ": { "description": "Sample note"} }}'; Axios.post('https://domain.myfreshworks.com/crm/sales/api/phone_calls', dataString, { headers: headers, }) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); });
问题根因
- 代码层面错误:Authorization请求头值缺失
token=前缀,和cURL的头信息不一致,会直接导致鉴权失败。 - CORS错误根因:cURL是不受浏览器同源策略限制的客户端,所以可以直接调用第三方接口;但浏览器环境下,Freshworks CRM的接口服务没有配置允许你当前前端域名的跨域访问权限,哪怕请求参数、头信息完全正确,直接从前端页面调用也会被浏览器拦截触发CORS错误,这个问题无法仅靠修改前端Axios写法解决。
正确实现方案
- 跨域问题解决
- 生产环境:不要在前端浏览器环境直接调用Freshworks接口,将该请求迁移到你的自有后端服务实现,前端仅调用自有后端接口,由后端发起对Freshworks的请求后将结果返回前端,后端请求不受同源策略限制。
- 本地开发调试:可以通过构建工具(Vite/Webpack)的devServer代理配置,将接口请求转发到Freshworks地址,绕过浏览器跨域校验;也可以临时启动关闭跨域校验的浏览器实例做调试。
- 等价Axios代码(可直接用于后端/代理场景)
不需要手动拼接JSON字符串,直接传JS对象即可,Axios会自动完成序列化,减少转义错误:
// 按需引入axios,前端环境按项目现有引入方式即可,无需重复引入 import axios from 'axios'; const headers = { 'Content-Type': 'application/json', // 补全缺失的token=前缀,和cURL头完全一致 'Authorization': 'Token token=sfg999666t673t7t82' }; const requestData = { phone_call: { call_direction: true, targetable_type: "contact", targetable: { id: "1", first_name: "Jane", last_name: "Sampleton (sample)", // 注意字段名末尾的空格必须保留,和cURL参数完全一致,否则会参数校验失败 "work_number ": "5304915427", "mobile_number ": "11919457004 " }, "note ": { description: "Sample note" } } }; axios.post('https://domain.myfreshworks.com/crm/sales/api/phone_calls', requestData, { headers }) .then(response => { console.log(response.data); }) .catch(error => { console.error('请求失败:', error); });
注意:原cURL参数中
work_number、mobile_number、note三个字段名末尾带有空格,实现时必须完全保留,不能随意删除,否则会被接口判定为参数缺失。
内容的提问来源于stack exchange,提问作者Bayoguzhan
相关产品推荐
相关产品推荐

