首页 > 解决方案 > 在本地运行 html 和 php 页面时避免跨源错误

问题描述

我在一个目录中有文件 test.html 和 test.php:

测试.html:

<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.js"></script>
</head>

<body>
<div id="root"></div>
<script type="text/babel">


class NameForm extends React.Component {

    componentDidMount(){
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
                console.log(xmlHttp.responseText)
            }
        }.bind(this)

        xmlHttp.open("GET","test.php",true)
        xmlHttp.send(null)
        event.preventDefault()
    }

    render() {
        return (<div/>)
    }
}

ReactDOM.render(
    <NameForm />,
    document.getElementById('root')
);


</script>
</body>

测试.php

<?php
header("Access-Control-Allow-Origin: http://localhost:1113")
header("Access-Control-Allow-Methods: GET, PUT, POST")
echo "this is a test"
?>

我可以在网站上运行这些,但不能在我的计算机上运行,​​我希望能够在本地运行它们以进行测试。我试图通过在 php 文件中添加标题来解决这个问题,但这仍然不起作用。我怎样才能解决这个问题?谢谢

标签: phphtml

解决方案


推荐阅读