You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Instascan扫码数据无法通过GET/POST传递至PHP的问题求助

问题解决方案

核心问题分析

PHP返回Error: This endpoint only accepts GET requests.,说明服务器接收到的请求方法并非GET,即便你在JS中明确指定了method: 'GET'。常见原因包括请求路径错误导致重定向、浏览器缓存干扰、服务器配置修改了请求方法等。

分步排查与修复

1. 验证请求路径正确性

  • 检查JS中请求URL的路径:如果HTML页面位于子目录(比如/scan/index.html),而Table.php在网站根目录,需要将路径改为../Table.php
  • 打开浏览器开发者工具的Network面板,查看请求的Request URL是否指向正确的PHP文件,同时确认请求的Status Code不是404或301/302重定向

2. 禁用fetch缓存

浏览器缓存可能导致请求异常,给fetch添加缓存控制参数:

sendToPHP: function (content) {
  var url = 'Table.php?content=' + encodeURIComponent(content);
  fetch(url, {
    method: 'GET',
    cache: 'no-cache' // 强制禁用缓存
  })
  // ... 后续代码保持不变
}

3. 调试实际请求方法

修改PHP代码,输出完整服务器变量,确认实际接收到的请求方法:

<?php
// 输出所有服务器变量,重点查看REQUEST_METHOD
var_dump($_SERVER);
?>

在Network面板查看响应,确认REQUEST_METHOD的实际值,以此判断请求是否被篡改。

4. 改用POST方法(规避GET潜在问题)

如果GET请求始终异常,切换到POST方法尝试:

修改JS代码:

sendToPHP: function (content) {
  fetch('Table.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: 'content=' + encodeURIComponent(content),
    cache: 'no-cache'
  })
  .then(function(response) {
    if (response.ok) {
      console.log('Content sent to PHP successfully');
      return response.text();
    } else {
      console.error('Error sending content to PHP');
      throw new Error('Error sending content to PHP');
    }
  })
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {
    console.error('Error:', error);
  });
}

修改PHP代码适配POST:

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (isset($_POST['content'])) {
        $content = $_POST['content'];
        echo "Scanned content received via POST: " . $content;
        // 后续可添加数据库验证逻辑
    } else {
        echo "Error: 'content' parameter is missing.";
    }
} elseif ($_SERVER["REQUEST_METHOD"] === "GET") {
    if (isset($_GET['content'])) {
        $content = $_GET['content'];
        echo "Scanned content received via GET: " . $content;
    } else {
        echo "Error: 'content' parameter is missing in query string.";
    }
} else {
    echo "Error: This endpoint accepts GET and POST requests only.";
}
?>

5. 检查服务器配置

  • 确保XAMPP的Apache服务正常运行,暂时移除网站根目录下的.htaccess文件,排除重写规则对请求方法的影响
  • 确认PHP文件权限正常(XAMPP下默认权限无问题,但若手动修改过需检查)

内容的提问来源于stack exchange,提问作者Sherif Basem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 15:07:32