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

相关推荐
冰暮流星18 小时前
javascript之do-while循环
开发语言·javascript·ecmascript
2501_9444241220 小时前
Flutter for OpenHarmony游戏集合App实战之连连看路径连线
android·开发语言·前端·javascript·flutter·游戏·php
C系语言20 小时前
python用pip生成requirements.txt
开发语言·python·pip
燃于AC之乐20 小时前
深入解剖STL Vector:从底层原理到核心接口的灵活运用
开发语言·c++·迭代器·stl·vector·源码分析·底层原理
星火开发设计1 天前
C++ 数组:一维数组的定义、遍历与常见操作
java·开发语言·数据结构·c++·学习·数组·知识
TTGGGFF1 天前
控制系统建模仿真(一):掌握控制系统设计的 MAD 流程与 MATLAB 基础运算
开发语言·matlab
2501_944424121 天前
Flutter for OpenHarmony游戏集合App实战之贪吃蛇食物生成
android·开发语言·flutter·游戏·harmonyos
利刃大大1 天前
【Vue】Vue2 和 Vue3 的区别
前端·javascript·vue.js
Lhuu(重开版1 天前
JS:正则表达式和作用域
开发语言·javascript·正则表达式
仙俊红1 天前
Java Map 家族核心解析
java·开发语言