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.

    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能