简体   繁体   中英

Proxying in development using Create React App

I'm building a React application that I started with create-react-app. In their documentation, they describe using a proxy server for API calls during development. I want to use this for when I make requests to my MAMP server for php files. However, the requests aren't being proxied to the assigned, it's still the webpack dev server serving it.

The create react app documentation says to put a line into the package.json file to set up the proxy. I've put "proxy": " http://localhost " in it (the MAMP server is running on port 80). The php file I'm trying to serve is in an "api" folder in the same directory as index.html

here's the request:

$.ajax({
     url: "/api/test.php"
     success: response=>{
     console.log(response);
     }
});

and test.php simply says: print("success")

But the console is reading:

<?php
print("success")
?>

which means it's the dev server, not the apache server that's serving the file. How can I fix this?

From the docs:

The development server will only attempt to send requests without text/html in its Accept header to the proxy.

https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development

Can you check the Network tab in the devtools and make sure the request Accept header is different from text/html . In case that is the problem this link could help you.

You are making an ajax request from your localhost to a different domain. this is counted as CORS request. to circumvent this you need to use proxy. since proxy is the part of the create react app, your browser assumes it is always pointed to the create-react-app, browser does not know that proxy is there. to solve the issue follow those steps:

In the client side directory:

npm i http-proxy-middleware --save

Create setupProxy.js file in client/src. No need to import this anywhere. create-react-app will look for this directory

Add your proxies to this file.

const proxy=require("http-proxy-middleware")
module.exports=function(app){
    app.use(proxy(['/api'],{target:"http://localhost:80"}))}

We are saying that make a proxy and if anyone tries to visit the route /api on our react server, automatically forward the request on to localhost:80.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM