
配置 php-express: 在 express 服务器中配置 php-express 中间件。
// server.js
const express = require('express');
const path = require('path');
const phpExpress = require('php-express')({
binPath: 'php' // 确保 PHP 可执行文件路径正确
});
const app = express();
const port = 3001; // 选择一个未被占用的端口
app.set('views', path.join(__dirname, 'views/php'));
app.engine('php', phpExpress.engine);
app.set('view engine', 'php');
app.all(/\.php$/, phpExpress.router); // 处理所有 .php 请求
app.listen(port, () => {
console.log(`Express server listening at http://localhost:${port}`);
});创建 PHP 文件: 在 views/php 目录下创建 PHP 文件。
mkdir -p views/php touch views/php/hello.php
<?php echo "Hello from PHP!"; ?>
React 应用发起 HTTP 请求: 在 React 应用中使用 fetch 或 axios 等工具向 Express 服务器发起 HTTP 请求。
// React 组件
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [message, setMessage] = useState('');
useEffect(() => {
fetch('http://localhost:3001/hello.php') // 替换为你的 Express 服务器地址
.then(response => response.text())
.then(data => setMessage(data))
.catch(error => console.error('Error:', error));
}, []);
return (
<div>
<p>{message}</p>
</div>
);
}
export default MyComponent;CORS 配置(如果需要跨域): 如果 React 应用和 Express 服务器运行在不同的域名或端口上,需要配置 CORS (跨域资源共享)。
// server.js
const cors = require('cors');
app.use(cors()); // 允许所有来源的跨域请求或者更精细的配置:
立即学习“PHP免费学习笔记(深入)”;
const cors = require('cors');
const corsOptions = {
origin: 'http://localhost:3000', // 允许你的 React 应用的域名
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions));注意事项
总结
php-express 不能直接在 React 应用中使用,因为它需要运行在 Node.js 的 Express 框架之上。正确的做法是建立一个独立的 Express 服务器,并使用 php-express 来处理 PHP 文件。React 应用可以通过 HTTP 请求与该服务器进行通信。 这种方式虽然可行,但如果不是必须同时使用 PHP 和 Node.js,使用其他服务器 (如 Nginx) 来运行 PHP 通常是更好的选择。
以上就是# 在 React 应用中使用 php-express 的正确方法的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号