React proxy не работает

create-react-app doesn’t work with proxy

I use create-react-app to bootstrap my react app, I did this in my package.json

«proxy»:»http://localhost:3001″ because my api server is running on 3001, but I fire request using axios, it still point to port 3000, any clue what is missing? restarted my app several times it still the same.

12 Answers 12

In your package.json add:

Please restart both your server ( backend app ) and front-end ( Create React App )

Make sure that your post request with axios it’s like below:

This example above it’s from my environment and works as well. Notice that proxy works only for development mode

Ensure your code that has the right slash in url in proxy and in axios post both

Try to remove absolute path for request, and use relative path instead.

Example

Note: Do not use http://localhost:3000/api/auth/register as the request URI, it (React server) will automatically proxying the request, and the API request will serve from 3001 port.

Issue is in webpack config file,with your own starter pack just set webpack.dev.js as in code bellow

and set appropriate localhost for your server and restart dev-server. In «create-react-app» webpack config files should be on path /node_modules/react-scripts/config , make changes as in code above and restart dev-server and you should be fine. On this path are webpack.dev.js and webpack.prod.js .

I had this problem and I did everything «correct». For me GET requests were going to my proxy but not POST! I got Request Aborted error.

Discovered solution by accident that my data : < key: value>needed to be properly quoted as data : < "key": value >.

Replace your proxy config with this: «proxy»: «http://127.0.0.1:5000», Make sure your proxy is added in client side of package.json and do a hard restart using ctrl+c after moving proxy config to client side.

I know this post is old but I recently had the same issue.

What fixed it for me was using the npm package axios to make API requests instead of the native JavaScript fetch API.

I didn’t look deep enough to see what request headers axios was doing differently than fetch, but everything works fine for me now.

I started with create-react-app, then added Node.js Express server (on Mac OS). After reading many solutions, restarting the server many times, I was still struggling to make it work with the proxy and be able to fetch(‘/api/hello’). Here is what actually works for me:

I restarted my computer (it apparently worked for some people). I discovered later that devServer was defined twice in webpack.config.js.

Читайте также:  Сервис гугл карты не работает

I read the answer that problem can cause using fetch instead of axios. Is not true, fault is incorrect request/body (you need look in your code).

For all who is looking for answers pleas be aware that is different solution if you create app by creat-react-app and don’t have a webpack.config.js. Then enough what you need to set up is adding proxy to your package.json

How should look proper fetch request:

For better debugging is good add a printscreen of network tab from dev tools

Источник

proxy not working for react and node

I’m having issues with the proxy I set up.

This is my root package.json file:

My client package.json file:

I’ve set up express on my server side to run on port 5000. Whenever I make a request to the server, ie :

The request always goes to

Can someone point out what i have to do to fix this issue so that the request actually goes to port 5000?

15 Answers 15

I experienced this issue quite a lot of times, and I figured it’s because of the cache. To solve the issue, do the following

@mkoe said that he was able to solve this issue simply by deleting the package-lock.json file, and restarting the app, so give that a try first. If that doesn’t resolve it, then do the following.

  1. Stop your React app
  2. Delete package-lock.json file and the node_modules directory by doing
    rm -r package-lock.json node_modules
    in the app directory.
  3. Then do npm install in the app directory.

Now your proxy in the package.json will not have any issues.

The reason the react application is still pointing at localhost:8080 is because of cache. To clear it , follow the steps below.

  1. Delete package-lock.json and node_modules in React app
  2. Turn off React Terminal and npm install all dependencies again on React App
  3. Turn back on React App and the proxy should now be working

This problem has been haunting me for a long time; but if you follow the steps above it should get your React application pointing at the server correctly.

Источник

proxy in package.json not working #1378

Comments

shabanraza commented Jan 12, 2017 •

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

The text was updated successfully, but these errors were encountered:

viankakrisna commented Jan 12, 2017

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 commented Jan 12, 2017

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

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.

seanmccay commented Oct 18, 2017 •

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

Welcome to React

To get started, edit src/App.js and save to reload.

Читайте также:  Мама нашла способ объяснить детям почему извинения не всегда работают для этого нужен лист бумаги

Also, here are some proposals.

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

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

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.

viankakrisna commented Oct 18, 2017 •

You need to return your response.json()

seanmccay commented Oct 18, 2017

@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 commented Oct 18, 2017

Ah, try to change the proxy setting to

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

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

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 commented Oct 19, 2017

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:

‘front-end’ the the React app.

The proxy setting is:

which works when the fetch request looks like:

this renders my data like so:

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.

Источник

Настройка proxy в package.json

Создал две папки с проектами creat-react-app и laravel. Для тестирования использую Open Server.

Читайте также:  Не удалось настроить обновления windows server 2008 r2

Для полной картины распишу:
/OSPanel/domains/laravel
/OSPanel/domains/react

В файле package.json можно указать proxy: «proxy»: «http://laravel.loc».
Если из директории react запустить команду yarn run start , переходим на http://localhost:3000/, то react взаимодействует с laravel. Rest API работает.

А если запустить через Open Server react («http://react.loc»), где указана точка входа build, то сайт загружается, но не взаимодействует с бэкендом.

Где в сборке указывается proxy? Или как заставить работать.

Помощь в написании контрольных, курсовых и дипломных работ здесь.

Распаковка package.json
Сообственно вопрос. Скачал и установил на виндовс 10 node.js Запустил консоль Win + R. Как дальше.

Зависимости версий в Package.json
Всем привет. Вообщем создаю из студии проект на ангуляр. Всё работает. Подключаю в него метериал.

Install пакетов через package.json
Гуру посоветуйте что почитать. Пишу «для себя» в Notepad++ на 3х Win-машинах(включая «чужие»).

gulp: назначение файла package.json
Сообщение вынесено из темы: https://www.cyberforum.ru/javascript/thread1724805.html whiteapps.

Источник

React App Proxy Error: Could Not Proxy Request

I am working on a group project that was deployed on Heroku, but now I need to do further work on it and am trying to get it to run locally again. It is a React app that uses MongoDB. I cloned the repo and did npm install in both the root folder and the client folder. When I enter npm run dev, the page comes up, but the the functionality is not working. When I try to sign in, sign up, or submit photos I get errors:

From the terminal:

From the console:

I looked at the error log and it seems like the server is refusing to make the connection. I can’t figure out what the problem is. The thing that confuses me the most is that my other team member also cloned the repo and claims everything is working for him. It was also functional while deployed on Heroku. Is there a particular setting on my computer that could be causing a problem? My firewall is turned off. In case it is an issue with the code, here is some of it:

server.js:

package.json:

api-routes.js

I would greatly appreciate any advice offered to fix this problem. I’ve been working on this for several days and can’t make it work. I am fairly new to coding — and completely new to React — and I’m getting very discouraged. Thank you in advance.

UPDATE Thanks for the quick responses! After looking through my files I realized I didn’t have a .env file, so there were no keys for the Watson api or AWS. I added one and the proxy error went away. But now I’m still having other errors.

In the app, you fill out the sign up form and then it takes you to the sign in page. I add my name and password to the sign up page, but I don’t think it is taking in the information. When I try to sign in, my name and/or password is apparently invalid. (The only restrictions on passwords in the model is that it must be 6 characters.) When I try to sign in I get the following in the console:

Now I’m wondering if this is a problem with the database.

Источник

Оцените статью