React+PHP开发CRUD时PUT请求遇CORS跨域错误求助
后台管理面板PUT请求CORS错误排查
我正在开发带CRUD操作的网站后台管理面板,API部署在子域名上。目前GET(所有联系人、单个联系人)、POST(添加联系人)功能都正常,但PUT更新联系人的请求卡了好几天。预填充表单没问题,提交时出现以下CORS错误:
Access to XMLHttpRequest at 'https://api.itisgoodtohave.me/contacts/update.php' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. PUT https://api.itisgoodtohave.me/contacts/update.php net::ERR_FAILED Uncaught (in promise) AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
对应的update.php代码:
<?php header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: *"); header("Access-Control-Allow-Methods: *"); include 'DbConnection.php'; $objDb = new DbConnection; $conn = $objDb->connect(); $method = $_SERVER['REQUEST_METHOD']; if ($method = "POST") { $contact = json_decode(file_get_contents('php://input')); $sql = "UPDATE contacts SET name=:name, email=:email, phone=:phone WHERE id=:id"; $stmt = $conn->prepare($sql); $stmt->bindParam(':id', $contact->id); $stmt->bindParam(':name', $contact->name); $stmt->bindParam(':email', $contact->email); $stmt->bindParam(':phone', $contact->phone); if ($stmt->execute()) { $response = ['status' => 1, 'message' => "Contact updated sucessfully."]; } else { $response = ['status' => 0, 'message' => "Could not update contact."]; } echo json_encode($response); } else { echo "some error occured"; } ?>
EditContact.js代码:
import React from 'react'; import axios from 'axios'; import { useState, useEffect } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; export default function EditContact() { const [inputs, setInputs] = useState([]) const navigate = useNavigate(); const { id } = useParams(); useEffect(() => { showContact(); }, []) function showContact() { axios.get(`https://api.mywebsite.com/contacts/single_read.php/?id=${id}`) .then(function(response) { setInputs(response.data); }) } const handleChange = (event) => { const name = event.target.name; const value = event.target.value; setInputs(values=> ({...values, [name]: value})); console.log(inputs) } const handleSubmit = (event) => { event.preventDefault(); axios.put('https://api.mywebsite.com/contacts/update.php', inputs) .then(function(response){ console.log(response) navigate('/admin/contacts') }) } return ( <div> <h3>Edit Contact</h3> <form onSubmit={handleSubmit}> <label>Name</label> <input defaultValue={inputs.name} type="text" name="name" onChange={handleChange} /> <br /> <label>Email</label> <input defaultValue={inputs.email} type="text" name="email" onChange={handleChange} /> <br /> <label>Phone</label> <input defaultValue={inputs.phone} type="text" name="phone" onChange={handleChange} /> <br /> <button type="submit">Save</button> </form> </div> ) }
Postman测试所有接口(GET、POST、PUT、DELETE)都正常,数据库能正常更新,但前端PUT请求始终报CORS错误,求解决思路。
排查与解决方向
修复条件判断错误
update.php里的if ($method = "POST")是赋值操作而非比较,前端用PUT请求,所以该条件永远不会触发,所有非POST请求都会走到else分支输出纯文本错误,导致CORS验证失败。需改为:if ($method === "PUT") { // 原更新逻辑 }处理OPTIONS预请求
浏览器发送PUT前会先发送OPTIONS预请求,检查服务器是否允许该方法。当前代码未处理OPTIONS请求,导致预请求返回非200状态。添加以下代码处理OPTIONS:if ($method === "OPTIONS") { http_response_code(200); exit(); }统一响应格式
确保所有响应都是JSON格式,添加Content-Type头,并把else分支的错误输出改为JSON:header("Content-Type: application/json"); // ... } else { echo json_encode(['status' => 0, 'message' => "Invalid request method"]); }确认API地址一致性
前端PUT请求地址是https://api.mywebsite.com/...,但错误信息里显示的是https://api.itisgoodtohave.me/...,检查是否存在域名不一致的问题,保持前后端API地址统一。
内容的提问来源于stack exchange,提问作者Katja
相关产品推荐
相关产品推荐

