create-react-app icon indicating copy to clipboard operation
create-react-app copied to clipboard

proxy in package.json not working

Open shabanraza opened this issue 9 years ago • 30 comments

I have defind a proxy url in package.json but it getting my localhost url before api path

{
  "name": "fanmojoReact",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "babel-core": "^6.20.0",
    "babel-loader": "^6.2.9",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "css-loader": "^0.26.1",
    "eslint": "^3.12.2",
    "eslint-config-standard": "^6.2.1",
    "eslint-config-standard-react": "^4.2.0",
    "eslint-plugin-node": "^3.0.5",
    "eslint-plugin-promise": "^3.4.0",
    "eslint-plugin-react": "^6.8.0",
    "eslint-plugin-standard": "^2.0.1",
    "react-scripts": "0.8.4",
    "style-loader": "^0.13.1",
    "sw-precache": "^4.2.2",
    "sw-precache-webpack-plugin": "^0.7.0",
    "webpack": "^1.14.0"
  },
  "dependencies": {
    "es6-promise": "^4.0.5",
    "isomorphic-fetch": "^2.2.1",
    "lodash": "^4.17.4",
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "react-redux": "^5.0.1",
    "react-router": "^3.0.0",
    "react-router-redux": "^4.0.7",
    "redux": "^3.6.0",
    "redux-act": "^1.1.0",
    "redux-logger": "^2.7.4",
    "redux-router": "^2.1.2",
    "redux-saga": "^0.13.0",
    "webpack-dev-server": "^1.16.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build && sw-precache --config=sw-precache-config.js",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "proxy": "http://172.21.25.169:3000"
}

shabanraza avatar Jan 12 '17 09:01 shabanraza

how do you test your proxy? using fetch / ajax / browser direct to url? the proxy in create react app only works when it's a fetch or ajax request.

viankakrisna avatar Jan 12 '17 14:01 viankakrisna

https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#proxying-api-requests-in-development

The development server will only attempt to send requests without a text/html accept header to the proxy.

viankakrisna avatar Jan 12 '17 14:01 viankakrisna

This is likely to be the issue: https://github.com/facebookincubator/create-react-app/issues/1378#issuecomment-272182020.

It's a bit counter-intuitive but the best we can do to support both use cases (client-side routing and proxying).

Let me know if the problem is different and I can reopen.

gaearon avatar Jan 12 '17 14:01 gaearon

@gaearon I am having this issue as well. I'm trying to use fetch to test the proxy.

class App extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      proposals: [],
    };
  }

//saw this sort of setup on a tutorial
  componentDidMount() {
    fetch('/api/proposals')
      .then(response => {
        console.log(response);
        response.json();
      })
      .then((proposals) => { 
        console.log(proposals);
        this.setState({ proposals }); 
      });
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
        <p className="App-intro">
          Also, here are some proposals.
        </p>
        <div className="proposal-container">
          {this.state.proposals}
        </div>
      </div>
    );
  }
}

in my package.json I have the proxy set like so:

"proxy": "http://localhost:56914"

which is where my .NET web api runs during dev.

I guess it's also worth noting that I use 'yarn start' to start up the webpack server. That corresponds to

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },

in my package.json right?

Would this have anything to do with file structure? I have the front end code at the root of my solution. I removed it from the initial folder it was in created by the 'create-react-app' tool. file-structure

seanmccay avatar Oct 18 '17 18:10 seanmccay

You need to return your response.json()

componentDidMount() {
    fetch('/api/proposals')
      .then(response => {
        console.log(response);
        return response.json();
      })
      .then((proposals) => { 
        console.log(proposals);
        this.setState({ proposals }); 
      });
}

viankakrisna avatar Oct 18 '17 21:10 viankakrisna

@viankakrisna - Ah, I didn't notice that. The underlying issue is still that the fetch makes a call to 'localhost:3000/api/proposals' instead of 'localhost:56914/api/proposals' despite having the proxy property set in package.json. What am I missing in that regard?

Thanks for the response 😄

seanmccay avatar Oct 18 '17 21:10 seanmccay

Ah, try to change the proxy setting to

"proxy": "http://localhost:56914/api"

and restart the dev server. IIRC the proxy setting need to have a namespace path defined.

viankakrisna avatar Oct 18 '17 21:10 viankakrisna

Hmmm. That didn't seem to do it either. I changed my api's port to 5000 in case I had hit some upward limit or something and updated the proxy setting to

"proxy": "http://localhost:5000/api"

I also tried adding a trailing '/ ' onto the end of the proxy as well as removing the first '/ ' from the fetch url and that didn't make a difference.

I made sure to restart the webpack server with each change to proxy...

I haven't received any errors about the proxy so far...

seanmccay avatar Oct 18 '17 22:10 seanmccay

Yeah, I can confirm an issue, and expand: If I navigate to the same route pointed in proxy with usual <a href='... />, proxy is working, but with ajax/fetch/axios I'm getting call to :3000

2017-10-19 6:41 GMT+08:00 Sean McCay [email protected]:

Hmmm. That didn't seem to do it either. I changed my api's port to 5000 in case I had hit some upward limit or something and updated the proxy setting to

"proxy": "http://localhost:5000/api"

I also tried adding a trailing '/ ' onto the end of the proxy as well as removing the first '/ ' from the fetch url and that didn't make a difference.

I haven't received any errors about the proxy so far...

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/facebookincubator/create-react-app/issues/1378#issuecomment-337748619, or mute the thread https://github.com/notifications/unsubscribe-auth/ACJseZ58w_FjH4KhbnbV8JBAj235c2R1ks5stn6KgaJpZM4Lhgrq .

JustFly1984 avatar Oct 18 '17 23:10 JustFly1984

Also I have an issue with https:// and proxy

If I wanna use HTTPS=true in npm script, proxy doesn't work at all

2017-10-19 7:33 GMT+08:00 Alexey Lyahov [email protected]:

Yeah, I can confirm an issue, and expand: If I navigate to the same route pointed in proxy with usual <a href='... />, proxy is working, but with ajax/fetch/axios I'm getting call to :3000

2017-10-19 6:41 GMT+08:00 Sean McCay [email protected]:

Hmmm. That didn't seem to do it either. I changed my api's port to 5000 in case I had hit some upward limit or something and updated the proxy setting to

"proxy": "http://localhost:5000/api"

I also tried adding a trailing '/ ' onto the end of the proxy as well as removing the first '/ ' from the fetch url and that didn't make a difference.

I haven't received any errors about the proxy so far...

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/facebookincubator/create-react-app/issues/1378#issuecomment-337748619, or mute the thread https://github.com/notifications/unsubscribe-auth/ACJseZ58w_FjH4KhbnbV8JBAj235c2R1ks5stn6KgaJpZM4Lhgrq .

JustFly1984 avatar Oct 18 '17 23:10 JustFly1984

Ok, so I've gotten past this but I'm not sure if I'm getting the expected behavior. I did a lot of messing around with this and I kinda think it came down to file structure and paths not being correct. @JustFly1984, what's your file structure look like?

Earlier I showed that I had taken all of the react code and stuck it in the root path. Then I scrapped that and used 'create-react-app' to create an app inside of my api's web project.

Finally I moved the react apps entire folder (not just its contents) to the root and it looks like it's ok with that. I ejected from CRA in order to look at scripts and play around with them, but the only changes I made were to add logging. Here's the current structure:

file-structure

'front-end' the the React app.

The proxy setting is:

"proxy": "http://localhost:5000/api"

which works when the fetch request looks like:

fetch('/proposals')
      .then(response => {
        console.log(response);
        return response.json();
      })
      .then((values) => { 
        console.log(values);
        this.setState({ proposals: values.toString()}); 
      });

this renders my data like so:

rendering-fetch-data

What is the expected behavior for the proxy? I'm seeing that the request is still sent to port 3000 in the JS console, but I'm getting my data from my api... I can go to localhost:5000/api/proposals in the browser and get my raw json.

Should the path 'localhost:3000/api/proposals' work? That renders my app component with all of the data. I feel like that path shouldn't work, but I don't really know much about React and Webpack or best practice for this type of work yet.

seanmccay avatar Oct 19 '17 16:10 seanmccay

I changed webpack.config.js and fixed.

https://github.com/facebook/create-react-app/issues/248#issuecomment-235863889

dgncn avatar Feb 28 '18 07:02 dgncn

request the whole URL 'http://localhost:5000' in the fetch , it will cause an error which is this:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. `

The browser prohibits cross-origin requests, you have to 'say something to him' to make him allow it this time: to solve this, you have to set the mode to cors (client side) with

fetch("http:/localhost:3000", {mode: cors})

This isn't enough, you have to make the server support the cors mode too, so you'll have to install the cors middleware:

npm install cors

then in your app.js (or what ever ou server file is)

app.use(cors())

you can visit the github repo of the cors module here : https://github.com/expressjs/cors

belhassen07 avatar Mar 27 '18 13:03 belhassen07

I just had a similar problem: Immediately, the proxy didn't work anymore (while it did a perfect job the day before). The problem obviously was another (stall) node process running in the background exposing a server on the exact same port I tried to forward to. The only strange thing was that I was even able to start this API server on the same port without any warning/error! So for me the solution was killing all node processes.

scriptify avatar May 09 '18 19:05 scriptify

Folks, make sure you did not put your "proxy" entry in the "scripts" key of package.json!

I'm a giant derp and realized I had done this (which is wrong):

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "server": "node devserver.js",
    "proxy": "http://localhost:5000"
  },

I should have done this, which is correct:

"proxy": "http://localhost:5000",
"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "server": "node devserver.js"
  },

Don't be a derp like me.

illepic avatar Jul 08 '18 19:07 illepic

@scriptify Worked for me :+1: :)

xUser5000 avatar Sep 04 '18 12:09 xUser5000

killall node

For anyone wanting to stop all node processes.

illepic avatar Sep 06 '18 21:09 illepic

Hey, I am having a weird issue where I have a proxy value added in my package.json file but when I am trying to connect with my server using axios, I see that my app gets directed to port 300 which is the default path for react app. my node.js server is running on port 5000. Any ideas, why this might be happening ??

sirdarthvader avatar Oct 24 '18 22:10 sirdarthvader

Hello. I've just had similar trouble, and i was seeing in the console the same client (localhost:3000) requests failing. But i actually did not have the server code (routes) not correctly setup. For example, i copied code from other sources and didn't notice that, i had in the code one route that worked: client: axios.post('/api/setup', {...}); server: router.post("/setup", function(req,res){ // a.s.o but this route did not work: client: axios.get('/api/get'); server: app.get('/get', function (req,res){ //a.s.o

Please notice between the two server lines, the route configuration: app vs. router !!

and way below: app.use("/api", router);

So even if the console shows failure with the client URL (e.g. localhost:3000), it may be that the server route is not setup, as in my case.

aluciffer avatar Nov 06 '18 21:11 aluciffer

I tried checking the same on my end, I was able to see that the routes are working when I am trying from postman. I think the routes are setup correctly. I am using express router but I still don't think why that should be any different.

Thanks Ashish Singh

On Wed, Nov 7, 2018 at 2:51 AM aluciffer [email protected] wrote:

Hello. I've just had similar trouble, and i was seeing in the console the same client (localhost:3000) requests failing. But i actually did not have the server code (routes) not correctly setup. For example, i copied code from other sources and didn't notice that, i had in the code one route that worked: client: axios.post('/api/setup', {...}); server: router.post("/setup", function(req,res){ // a.s.o but this route did not work: client: axios.get('/api/get'); server: app.get('/get', function (req,res){ //a.s.o

Please notice between the two server lines, the route configuration: app vs. router !!

and way below: app.use("/api", router);

So even if the console shows failure with the client URL (e.g. localhost:3000), it may be that the server route is not setup, as in my case.

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/facebook/create-react-app/issues/1378#issuecomment-436412514, or mute the thread https://github.com/notifications/unsubscribe-auth/Aau4vdCWiPYtIt6rUVEHg0cExgB1TJVkks5usf0-gaJpZM4Lhgrq .

sirdarthvader avatar Nov 08 '18 20:11 sirdarthvader