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

相关推荐
-To be number.wan29 分钟前
Python数据分析:numpy数值计算基础
开发语言·python·数据分析
HIT_Weston39 分钟前
107、【Ubuntu】【Hugo】搭建私人博客:模糊搜索 Fuse.js(三)
linux·javascript·ubuntu
Cx330❀1 小时前
【优选算法必刷100题】第038题(位运算):消失的两个数字
开发语言·c++·算法·leetcode·面试
Loo国昌1 小时前
深入理解 FastAPI:Python高性能API框架的完整指南
开发语言·人工智能·后端·python·langchain·fastapi
hoiii1872 小时前
16APSK/32APSK调制解调MATLAB仿真实现
开发语言·matlab·fpga开发
feifeigo1232 小时前
基于MATLAB的情感语音模板培训与识别实现方案
开发语言·matlab
JH30733 小时前
Java Spring中@AllArgsConstructor注解引发的依赖注入异常解决
java·开发语言·spring
码农水水3 小时前
米哈游Java面试被问:机器学习模型的在线服务和A/B测试
java·开发语言·数据库·spring boot·后端·机器学习·word
C++ 老炮儿的技术栈3 小时前
C/C++ 中 inline(内联函数)和宏定义(#define)的区别
开发语言·c++·git·算法·机器人·visual studio
我什么都学不会3 小时前
Python练习作业2
开发语言·python