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 是我需要的内容

相关推荐
曹轲恒7 小时前
Java中断
java·开发语言
施棠海8 小时前
监听与回调的三个demo
java·开发语言
時肆4858 小时前
C语言造轮子大赛:从零构建核心组件
c语言·开发语言
赴前尘8 小时前
golang 查看指定版本库所依赖库的版本
开发语言·后端·golang
de之梦-御风8 小时前
【C#.Net】C#开发的未来前景
开发语言·c#·.net
知乎的哥廷根数学学派9 小时前
基于数据驱动的自适应正交小波基优化算法(Python)
开发语言·网络·人工智能·pytorch·python·深度学习·算法
de之梦-御风9 小时前
【C#.Net】C#在工业领域的具体应用场景
开发语言·c#·.net
sunfove9 小时前
将 Python 仿真工具部署并嵌入个人博客
开发语言·数据库·python
Learner9 小时前
Python类
开发语言·python
X1A0RAN10 小时前
python 借助 paramiko 库执行 SSH命令报错:input is not a terminal 解决方式
开发语言·python·ssh