Laravel中如何获取HTTPS请求数据及解决解析异常问题
问题解决:Laravel无法解析HTTPS请求数据
客户端请求的核心错误
你当前的客户端代码存在两个关键问题:
- Content-Type与发送数据格式不匹配:你把JSON字符串作为请求体发送,但请求头的
Content-Type设为了application/x-www-form-urlencoded。Laravel会根据这个头按表单格式解析数据,导致整个JSON串被当作一个表单字段名,最终出现{"{\"email\":68,\"token\":\"945672295777710090\"}":null}这种异常格式。 - HTTPS请求模块错误:请求HTTPS接口应该使用Node.js的
https模块,而非http模块,否则可能出现请求异常。
修正后的客户端代码
const https = require('https'); // 替换http为https模块 var post_data = JSON.stringify({ email: email, token: token }); var post_options = { host: host_main, port: '443', path: new_user_list, method: 'POST', headers: { 'Content-Type': 'application/json', // 修改为JSON类型的Content-Type 'Content-Length': Buffer.byteLength(post_data) } }; var post_req = https.request(post_options, function(res) { // 用https.request替代http.request res.setEncoding('utf8'); res.on('data', function (chunk) { console.log(chunk); }); }); post_req.write(post_data); post_req.end();
Laravel端正确获取数据的方法
当客户端修正请求后,Laravel会自动解析JSON请求体,你可以用以下任意方式获取数据:
- 获取单个字段:
$request->input('email')或直接$request->email - 获取所有数据:
$request->all(),会返回包含email和token的关联数组
临时兼容方案(若无法修改客户端)
如果暂时无法调整客户端代码,可在Laravel端手动解析原始请求内容:
// 获取原始请求内容 $rawContent = $request->getContent(); // 解析JSON为数组 $data = json_decode($rawContent, true); // 获取字段值 $email = $data['email']; $token = $data['token'];
内容的提问来源于stack exchange,提问作者Phương Phạm
相关产品推荐
相关产品推荐

