Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proxy in package.json not working #1378

Closed
shabanraza opened this issue Jan 12, 2017 · 30 comments
Closed

proxy in package.json not working #1378

shabanraza opened this issue Jan 12, 2017 · 30 comments

Comments

@shabanraza
Copy link

shabanraza commented Jan 12, 2017

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"
}
@viankakrisna
Copy link
Contributor

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
Copy link
Contributor

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.

@gaearon
Copy link
Contributor

gaearon commented Jan 12, 2017

This is likely to be the issue: #1378 (comment).

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 gaearon closed this as completed Jan 12, 2017
@seanmccay
Copy link

seanmccay commented Oct 18, 2017

@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

@viankakrisna
Copy link
Contributor

viankakrisna commented Oct 18, 2017

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 }); 
      });
}

@seanmccay
Copy link

@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 😄

@viankakrisna
Copy link
Contributor

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.

@seanmccay
Copy link

seanmccay commented Oct 18, 2017

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...

@JustFly1984
Copy link

JustFly1984 commented Oct 18, 2017 via email

@JustFly1984
Copy link

JustFly1984 commented Oct 18, 2017 via email

@seanmccay
Copy link

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.

@dgncn
Copy link

dgncn commented Feb 28, 2018

I changed webpack.config.js and fixed.

#248 (comment)

@belhassen07
Copy link

belhassen07 commented Mar 27, 2018

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

@scriptify
Copy link

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.

@illepic
Copy link

illepic commented Jul 8, 2018

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.

@xUser5000
Copy link

@scriptify Worked for me 👍 :)

@illepic
Copy link

illepic commented Sep 6, 2018

killall node

For anyone wanting to stop all node processes.

@sirdarthvader
Copy link

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 ??

@aluciffer
Copy link

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.

@sirdarthvader
Copy link

sirdarthvader commented Nov 8, 2018 via email

@akshatBais
Copy link

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.

I have used request and it works with that too

@jeffdraymer
Copy link

Just an added note for those who may have missed this step: make sure the restart the server once you update the proxy so that the change will take effect. I spent too long trying to figure out why the change wasn't appearing until I tried turning it off and on again.

@sshakil
Copy link

sshakil commented Nov 22, 2018

make sure ur path is correct in fetch, i had a space which was causing this

@shiraze
Copy link

shiraze commented Nov 30, 2018

I had the same problem, and fixed it by increasing my proxy port number from 3001 to 6000 (on a Windows PC).
So, my package.json contains:
"proxy": "http://localhost:6000",

It might also be worth noting that a Fiddler trace still shows an attempt to go to port 3000 (port used by my react client), but my webservice is being hit!

@adrienrenaud
Copy link

Running both servers on a vm with the front ssh-forwarded to my local localhost, I couldn't access the proxy in the browser but it was working fine with curl from the remote. To have the proxy working on my local browser, I changed:
"proxy": "http://localhost:5000/api"

to

  "proxy": {
    "/api": {
      "target": "http://localhost:5000"
    }

@soggybag
Copy link

I had these same issues. Seems if I fetch('/') the root path, it returns the index.html from the React public folder. If I use any other path, fetch('/api') for instance, proxy works and points to the Express server.

Not sure if this is expected behavior, or why If it is?

@mrmckeb
Copy link
Contributor

mrmckeb commented Dec 23, 2018

@soggybag That is intended, has that been an issue for you?

@soggybag
Copy link

@soggybag That is intended, has that been an issue for you?

Yeah, I wasted some time wondering why I couldn't get to my root route.

@mrmckeb
Copy link
Contributor

mrmckeb commented Dec 24, 2018

Maybe we need to improve the docs here. I'd be happy for you to raise a PR to improve that if you'd like?

@ofonimefrancis
Copy link

Running both servers on a vm with the front ssh-forwarded to my local localhost, I couldn't access the proxy in the browser but it was working fine with curl from the remote. To have the proxy working on my local browser, I changed:
"proxy": "http://localhost:5000/api"

to

  "proxy": {
    "/api": {
      "target": "http://localhost:5000"
    }

When specified, "proxy" in package.json must be a string.
Instead, the type of "proxy" was "object".
Either remove "proxy" from package.json, or make it a string

How do you fix this?

@lock lock bot locked and limited conversation to collaborators Jan 9, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests