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.

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100