js ajax初次跨域请求

最近有个页面,要请求第三方的一个api,

postman里测试返回结果正常,状态正常

可在php js前端请求,返回错误,取不到任何有用信息,status = 0.

没接触过跨域,一直以为第三方接口问题,

后来知道还有跨域这一说法,就是http请求其他主机地址,浏览器是不允许的,会返回错误

解决:

在后端页面用php转发前端的请求,并加入跨域的标志

复制代码
public function send_RegisterPost() {
	  $url = 'http://www.baidu.com/text2audio';

	  $json =  $this->input->post('json');


	  $postdata = http_build_query($json);
	  $options = array(
		'http' => array(
		  'method' => 'POST',
		  'header' => 'Content-type:application/json',
		  'content' => $json,
		  'timeout' => 15 * 60 // 超时时间(单位:s)
		)
	  );
	  $context = stream_context_create($options);
	  $result = file_get_contents($url, false, $context);
	  $this->output->set_header("Access-Control-Allow-Origin: * ");
	  $data['dbData'] = $result;
	  out::code(10000,$data,"获取成功");
	  
	}

虽然前端ajax 还是在 error中,但status =200 statusText 是我需要的内容

相关推荐
ChoSeitaku13 小时前
07_static_JavaBean_继承_super/this
java·开发语言
hbugs00113 小时前
EVE-NG桥接外网的5种方式
开发语言·网络·php·eve-ng·rstp·流量洞察
wjs202414 小时前
Lua 字符串
开发语言
三品吉他手会点灯14 小时前
C语言学习笔记 - 33.数据类型 - printf函数的详细用法
c语言·开发语言·笔记·学习·算法
知行合一。。。14 小时前
Python--05--面向对象(继承,多态)
android·开发语言·python
csbysj202014 小时前
Vue3 样式绑定
开发语言
:12114 小时前
java继承
java·开发语言
ZC跨境爬虫14 小时前
跟着 MDN 学 HTML day_61:(构建反馈表单的结构化挑战)
前端·javascript·ui·html·音视频
小郑加油14 小时前
python学习Day15:综合训练——数据清洗与缺失值补充
开发语言·python·学习
完成大叔14 小时前
Agent入门:用本地模型从零搭建
开发语言·python·langchain