用PHP Rest API反应axios,如何编写baseurl

时间:2020-10-22 11:38:37

标签: php reactjs axios restapi

我正在做一个ReactJS前端应用程序,并从使用PHP Rest API创建的API中获取数据,但是我的react是在localhost:3000上托管的,但是我的php文件却在localhost:80上托管。所以不确定在react中如何写baseurl,直到现在它总是会出现一些错误。 我可以知道如何解决吗?谢谢。

错误:

public function getChilds()
{
    return $this->hasMany('App\Models\Menu', 'parent', 'id')->where(['group' => $this->group])->with('getChilds');
}

ReactJS:

Access to XMLHttpRequest at 'http://localhost/reacttest/src/api/read.php' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

xhr.js:184 GET http://localhost/reacttest/src/api/read.php net::ERR_FAILED

read.php:

import React from 'react';
// import logo from './logo.svg';
import './App.css';
import axios from "axios";

const baseUrl = "http://localhost:80/reacttest/src/api";

const sampleGet = async () => {
  const result = await axios.get(baseUrl + "/read.php");
  console.log(result);
};
const samplePost = async () => {
  const result = await axios.post(baseUrl + "/posts", {
    sampleData: "nabezap"
  });
  console.log(result);
};
const sampleDelete = async () => {
  const result = await axios.delete(baseUrl + "/posts/4");
  console.log(result);
};


function App() {
  return (
    <div className="App">
      <button onClick={sampleGet}>GET</button>
      <button onClick={samplePost}>POST</button>
      <button onClick={sampleDelete}>DELETE</button>
    </div>
  );
}

export default App;

api.php: enter image description here

1 个答案:

答案 0 :(得分:1)

基本网址是正确的(默认值为80),如果您在开发工具中检查“网络”标签,则会看到请求实际上已经发送出去并收到了预期的响应。

问题出在您的REST API上。线索出在错误中:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

这意味着服务器收到了请求,对其进行了处理并返回了响应-但未附加Access-Control-Allow-Origin: ‘http://localhost:3000’标头。当您的浏览器从API接收到响应时,会检查该标头,并在缺少响应时拒绝javascript访问响应数据。这是正常的。

在您的REST API上设置CORS是必须的。您正在使用什么框架(如果有)?知道后,我将使用更多信息来编辑此答案。