我已经建立了一个非常简单的 React 网站,但是我正在尝试放入一个 PHP 后端。
我遵循了本教程https://www.geeksforgeeks.org/how-to-connect-reactjs-as-a-front-end-with-php-as-a-back-end/
我不断收到控制台错误: CORS 策略已阻止从来源“http://localhost:8000/server.php”访问“http://localhost:8000/server.php”处的 XMLHttpRequest:没有“Access-Control-Allow-Origin”标头存在于请求的资源。
我的文件夹结构是这样的 前端 -php -- 服务器.php -src - 成分 --元素 --页面 ---测试.js --app.js
server.php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Credentials: true');
$user = $_POST['name'];
echo ("Hello from server: $user");
?>
testing.js
import { useState } from "react";
import $ from "jquery";
function Testing() {
const [name, setName] = useState("");
const [result, setResult] = useState("");
const handleChange = (e) => {
setName(e.target.value);
};
const handleSumbit = (e) => {
e.preventDefault();
console.log("Fire");
const form = $(e.target);
$.ajax({
method: "POST",
mode: 'no-cors',
crossDomain : true,
url: form.attr("action"),
data: form.serialize(),
success(data) {
console.log("succuess");
setResult(data);
},
});
};
return (
<div className="App">
<form
action="http://localhost:8000/server.php"
method="post"
onSubmit={(event) => handleSumbit(event)}
>
<label htmlFor="name">Name: </label>
<input
type="text"
id="name"
name="name"
value={name}
onChange={(event) => handleChange(event)}
/>
<br />
<button type="submit">Submit</button>
</form>
<h1>{result}</h1>
</div>
);
}
export default Testing;
app.js
import React from 'react';
import './App.css';
import Navbar from './elements/Navbar/index';
import Footer from './elements/footer';
import { BrowserRouter as Router, Routes, Route} from 'react-router-dom';
import { AppContainer } from "./styles";
import Home from './pages';
import About from './pages/about';
import Contact from './pages/contact';
import Testing from './pages/testing';
//import Exhibitions from './components/Exhibitions';
function App() {
return (
<Router>
<Navbar />
<AppContainer>
<Routes>
<Route exact path='/' element={<Home />} />
<Route path='/about' element={<About/>} />
<Route path='/contact' element={<Contact/>} />
<Route path='/testing' element={<Testing/>} />
</Routes>
</AppContainer>
<Footer />
</Router>
);
}
export default App;
任何人都可以帮助确定这里的问题吗,我阅读了其他一些堆栈溢出线程,其中人们遇到了类似的问题,但是当我尝试答案时,没有一个修复对我有用。
我添加到server.php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Credentials: true');
我添加的ajax请求
mode: 'no-cors',
crossDomain : true,
我还在我的 server.php 中尝试了以下内容:
header('Access-Control-Allow-Origin: http://localhost:3000/');
和
header('Access-Control-Allow-Origin: 127.0.0.1');