dongyuan6949 2017-12-05 03:07
浏览 92

从React到PHP文件的Ajax调用 - 不知道位置

Im creating a very basic login page and i'm trying to use php to verify the user login. Here is the code I'm using to access the php file.

 axios.post("login.php", {
    user: 'Fred',
    pass: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

The PHP file is located within the src folder of the react app.

  ── src
    │   ├── components
    │   │   ├── BrowsePage
    │   │   │   ├── BrowsePage.css
    │   │   │   ├── BrowsePage.js
    │   │   │   └── default.jpg
    │   │   ├── CreatePage
    │   │   │   ├── CreatePage.css
    │   │   │   └── CreatePage.js
    │   │   ├── Header
    │   │   │   ├── Header.css
    │   │   │   └── Header.js
    │   │   ├── LoginPage
    │   │   │   ├── LoginPage.css
    │   │   │   ├── LoginPage.js
    │   │   │   └── logo.svg
    │   │   ├── ProfilePage
    │   │   │   ├── ProfilePage.css
    │   │   │   └── ProfilePage.js
    │   │   └── RecPage
    │   │       ├── default.jpg
    │   │       ├── RecPage.css
    │   │       └── RecPage.js
    │   ├── index.css
    │   ├── index.js
    │   ├── login.php
    │   └── registerServiceWorker.js

When I make the call it logs

xhr.js:178 POST http://localhost:3000/login.php 404 (Not Found)

The current path to the php document does not work, and none of the others I've tried work. What is the path to make an axios call to this php document?

  • 写回答

1条回答 默认 最新

  • dsigg21445 2017-12-05 03:49
    关注

    You'll need to setup a server locally that your React application can proxy certain http requests to. This server will run your login.php script and authenticate the username/password. create-react-app looks for a proxy value in your package.json and tells webpack-dev-server to forward any calls to api/foobar to wherever you have declared that your back-end will be running.

    In your package.json add:

    "proxy": "http://localhost:8000"
    

    This tells React to forward requests made to http://localhost:3000/api/login to http://localhost:8000/api/login

    Then modify your axios call to look like this

    axios.post("/api/login", ..., ...).then()
    

    Next, you have to get your PHP server running on http://localhost:8000 and set up your server application to handle POST requests made to /api/login.

    I'm not a PHP guy but I've heard Laravel is nice to work with. It would be easier if your PHP backend was in its own directory completely.

    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站