权威的大连网站建设,网页设计结构,it程序员工资一般多少,网站域名备案查询系统前言 跨域#xff0c;一句话介绍#xff1a; 你要请求的URL地址与当前的URL地址#xff0c;协议不同、域名不同、端口不同时#xff0c;就是跨域。 步入正题
前端#xff0c;jQuery ajax请求
$.ajax({async: false,method: post,//URl和端口与后台匹配好#xff0c;当…前言 跨域一句话介绍 你要请求的URL地址与当前的URL地址协议不同、域名不同、端口不同时就是跨域。 步入正题
前端jQuery ajax请求
$.ajax({async: false,method: post,//URl和端口与后台匹配好当前情况后端是本地端口3000url: http://localhost:3000/api/getUserinfo,crossDomain: true,//这里的data是有两个参数没有可以注释data: {access_token: accessToken,code: urlCode},success: function(response) { console.log(response);//后台返回的是json数据通过response.参数名获取值//例如 var accessToken response.access_token;},error: function(xhr, status, error) {alert(error);}
});node.js后端使用cors跨域
const express require(express);
const cors require(cors);
const axios require(axios);
//前端无data参数的话body-parser可以不引入
const bodyParser require(body-parser);
const app express();// 设置 cors 中间件
app.use(cors());//前端没无data参数的话bodyParser的这两行可以忽略
//解析数据建议这两行一起使用除非你明确的知道只需要解析其中一种格式的请求体数据
//这一行代码是解析application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// 这一行代码是解析application/json
app.use(bodyParser.json())// 设置路由
app.post(/api/getuserinfo ,(req, res) {//获取前端的data参数无data需要注释掉const accessToken req.body.access_token;const code req.body.code;axios({//这里可以写外部其他公司的接口url: https://www.weixin.qq.com/cgi-bin/user/getuserinfo,method: post,params: {access_token: accessToken,code: code},headers: {Content-Type: application/json;charsetUTF-8},responseType: json}).then(response {res.json(response.data);}).catch(error {res.status(500).send(error.message);});
});// 启动服务监听3000端口
const server app.listen(3000, () {console.log(Server started listening at http://localhost:3000);
})如果req.body获取为{}请注意检查body-parser的引入和使用问题
//引入
const bodyParser require(body-parser);
//设置
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
//获取参数值
const 参数值 req.body.参数名1;bodyparser有以下几种常用解析方式 1bodyParser.json(options)解析json格式 2bodyParser.urlencoded(options)解析文本格式 3bodyParser.raw(options)解析二进制 4bodyParser.text(options)解析文本格式仅字符串
可以结合上面的内容一起看。
其他补充
Express的req.body返回为空的问题
Jquery的ajax默认的ContentType和数据格式
1.默认的ContentType的值为:application/x-www-form-urlencoded; charsetUTF-8 此格式为表单提交格式数据为key1value1key2value2的格式 2.虽然ajax的data属性值格式为:{key1:value1,key2:value2},但最后会转为key1value1key2value2的格式提交到后台 3.如果ajax要和springmvc交互key1value1key2value2的格式后台springmvc只需要定义对象或者参数就行了会自动映射。 4.如果springmvc的参数有RequestBody注解接收json字符串格式数据ajax必须将date属性值转为json字符串不能为json对象js对象会自动转为keyvalue形式。并且修改contentType的值为:application/json; charsetUTF-8,这样加了RequestBody注解的属性才能自定映射到值