Proxy error could not proxy request react

React App Proxy Error: Could Not Proxy Request, reactjs, proxy

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:

[1] Proxy error: Could not proxy request /api/account/signin from localhost:3000 to http://localhost:3001/.
[1] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).

From the console:

POST http://localhost:3000/api/account/signin 500 (Internal Server Error)
Uncaught (in promise) Error: Request failed with status code 500
    at createError (createError.js:16)
    at settle (settle.js:18)
    at XMLHttpRequest.handleLoad (xhr.js:77)

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:

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');  

const PORT = process.env.PORT || 3001;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

if (process.env.NODE_ENV === "production") {
    app.use(express.static("client/build"));
    const path = require('path');
    app.get('/', (req, res) => {
      res.sendFile(path.resolve(__dirname, 'client', 'build', 
'index.html'));
    });
}

mongoose.connect(
  process.env.MONGODB_URI || "mongodb://localhost:27017/leafy",
  {
    useNewUrlParser: true
  }
);

require("./routes/api-routes.js")(app);

app.listen(PORT, function () {
    console.log("App listening on PORT: " + PORT);
});

package.json:

{
  "name": "ai-img-recog",
  "version": "1.0.0",
  "description": "AI-powered image recognition",
  "main": "server.js",
  "scripts": {
    "server": "node server.js",
    "test": "echo "Error: no test specified" && exit 1",
    "start": "node server.js",
    "client": "npm run start --prefix client",
    "dev": "concurrently "node server.js" "npm run client"",
    "heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/deasydoesit/ai-img-recog.git"
  },
  "keywords": [
    "AI",
    "visual analysis",
    "image recognition"
  ],
  "author": "Christina",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/deasydoesit/ai-img-recog/issues"
  },
  "homepage": "https://github.com/deasydoesit/ai-img-recog#readme",
  "dependencies": {
    "aws-sdk": "^2.279.1",
    "axios": "^0.18.0",
    "bcrypt": "^2.0.1",
    "body-parser": "^1.18.3",
    "concurrently": "^3.6.0",
    "create-react-app": "^1.5.2",
    "dotenv": "^6.0.0",
    "express": "^4.16.3",
    "mongoose": "^5.2.4",
    "multer": "^1.3.1",
    "multer-s3": "^2.7.0",
    "path": "^0.12.7",
    "watson-developer-cloud": "^3.7.0"
  }
}

api-routes.js

require('dotenv').config();
const aws = require('aws-sdk');
const multerS3 = require('multer-s3');
const multer = require('multer');
const VisualRecognitionV3 = require('watson-developer-cloud/visual-recognition/v3');
const db = require('../models');
const mongoose = require('mongoose');


// Initialize Mongo
const MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost/leafy";
mongoose.Promise = Promise;
mongoose.connect(MONGODB_URI);
//---*

// Initiaize Watson Visual Recognition
const visualRecognition = new VisualRecognitionV3({
  version: process.env.WATSON_VERSION,
  iam_apikey: process.env.WATSON_APIKEY
});
//---*

// Initialize AWS
aws.config.update({
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  region: 'us-east-1'
});

const s3 = new aws.S3();

let upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: "leafy-me/public",
        key: function (req, file, cb) {
            console.log(file);
            let path = "https://s3.amazonaws.com/leafy-me/public/";
            let newImage = file.fieldname + Date.now() + ".jpg";
            path += newImage;
            cb(null, newImage);
        }
    })
});  
//---*

module.exports = function (app) {

  // Function 
  app.get('/api/user_trees/:token', function(req, res) {
    console.log(req.params.token);
    console.log(mongoose.Types.ObjectId(req.params.token));
    db.UserSession.find({_id: mongoose.Types.ObjectId(req.params.token)}) //req.params.token
        .then(function(session) {
          db.Post.find({user_id: session[0].userId})
            .then(function(trees) {
              console.log("hello");
              res.send(trees);
            })
            .catch(function(err) {
              return res.json(err);
            });
          })
          .catch(function(err) {
            return res.json(err);
          });
    });

  // Route for image upload to AWS, Watson processing, etc.
  app.post('/api/image/image-upload/:token', upload.single('photo'), function(req, res, next) {

      let token = req.params.token; 
      let user_id = '';
      db.UserSession.find({_id: mongoose.Types.ObjectId(req.params.token)})
        .then(function(res) {
          console.log(res);
          user_id = res[0].userId;
          console.log(res[0].userId);
        })
      // Set up Watson parameters

      let image_url =  req.file.location;
      const classifier_ids = ["trees_447821576"];
      const threshold = 0.6;

      let params = {
          url: image_url,
          classifier_ids: classifier_ids,
          threshold: threshold
      };
      //---*

      visualRecognition.classify(params, function(err, response) { // Watson request
          if (err) {
            console.log(err);
          }
          else //get Watson results back
            console.log(JSON.stringify(response, null, 2));
            let trees = response.images[0].classifiers[0].classes; // Access Watson returned tree types
            if (trees.length === 0) { // If there are no tree types, respond client that the image isn't recognized
              res.send("Image not recognized");
            } else if (trees.length === 1) { // If there is one tree type, make a database entry and return tree data to client
            // Mongo storage
              let result = {};
              result.path = image_url;
              result.name = trees[0].class;
              console.log(user_id);
              db.Tree.find({name: result.name})
                  .then(function(tree) {
                      result.user_id = user_id;
                      result.sciName = tree[0].sciName;
                      result.range = tree[0].range;
                      db.Post.create(result)
                          .then(function(dbPost) {
                              console.log(dbPost)
                              res.send(dbPost);
                          })
                          .catch(function(err) {
                              return res.json(err);
                          });
                  })
            //---*
              } else { // If there are more than one tree types identified, ask client for help.
                  res.send("Please pick one of these images");
              }
      });
  });

  // --------------sign up------------------------------------------------------------
  app.post('/api/account/signup', (req, res, next) => {
    const { body } = req;
    const {
      username,
      password
    } = body;

    if (!username) {
      return res.send({
        success: false,
        message: "Username required."
      });
    }

    if (!password) {
      return res.send({
        success: false,
        message: "Password required."
      });
    }

    db.User.find({
      username: username
    }, (err, previousUsers) => {
      if (err) {
        return res.send({
          success: false,
          message: "Error"
        });
      } else if (previousUsers.length > 0) {
        return res.send({
          success: false,
          message: "Username is taken."
        })
      }

      const newUser = new db.User();
      newUser.username = username;
      newUser.password = newUser.generateHash(password);
      newUser.save((err, user) => {
        if (err) {
          return res.send({
            success: false,
            message: "Server error"
          })
        }
        return res.send({
          success: true,
          message: "Sign Up successful!"
        })
      })
    })
  });

  // --------------sign in -----------------------------------------------------------
  app.post('/api/account/signin', (req, res, next) => {
    const { body } = req;
    const {
      username,
      password
    } = body;

    if (!username) {
      return res.send({
        success: false,
        message: "Username required."
      });
    }

    if (!password) {
      return res.send({
        success: false,
        message: "Password required."
      });
    }

    db.User.find({
      username: username
    }, (err, users) => {
      if (err) {
        return res.send({
          success: false,
          message: "Server Error"
        });
      }
      if (users.length != 1) {
        return res.send({
          success: false,
          message: "Invalid"
        })
      }

      const user = users[0];
      if (!user.validPassword(password)) {
        return res.send({
          success: false,
          message: "Invalid"
        })
      }

      const userSession = new db.UserSession();
      userSession.userId = user._id;
      userSession.save((err, doc) => {
        if (err) {
          return res.send({
            success: false,
            message: "Server Error"
          });
        }
        console.log(doc);
        return res.send({
          success: true,
          message: "Sign In successful",
          token: doc._id
        });
      });
    });
  });

  // --------------verify--------------------------------------------------------------
  app.get('/api/account/verify', (req, res, next) => {

    const { query } = req;
    const { token } = query;

    db.UserSession.find({
      _id: token,
      isDeleted: false
    }, (err, sessions) => {
      if (err) {
        return res.send({
          success: false,
          message: "Server Error"
        })
      }

      if (sessions.length != 1) {
        return res.send({
          success: false,
          message: "Invalid"
        })
      }

      else {
        return res.send({
          success: true,
          message: 'good'
        })
      }
    })
  })

  // ---------------logout-------------------------------------------------------------
  app.get('/api/account/logout', (req, res, next) => {
    const { query } = req;
    const { token } = query;

    db.UserSession.findOneAndUpdate({
      _id: token,
      isDeleted: false
    }, {
        $set: { isDeleted: true }
      }, null, (err, sessions) => {
        if (err) {
          return res.send({
            success: false,
            message: "Server Error"
          })
        }

        return res.send({
          success: true,
          message: 'good'
        })
      })
  })
};

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:

{data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config: 
adapter: ƒ xhrAdapter(config)
data: "{"username":"Christina","password":"password"}"
headers: {Accept: "application/json, text/plain, */*", Content-Type: "application/json;charset=utf-8"}
maxContentLength: -1
method: "post"
timeout: 0
transformRequest: {0: ƒ}0: ƒ 
transformResponse: {0: ƒ}
url: "/api/account/signin"
validateStatus: ƒ validateStatus(status)
xsrfCookieName: "XSRF-TOKEN"
xsrfHeaderName: "X-XSRF-TOKEN"
__proto__: Object
data: 
message: "Invalid"
success: false
__proto__: Object
headers: 
connection: "close"
content-length: "37"
content-type: "application/json; charset=utf-8"
date: "Tue, 14 Aug 2018 20:03:01 GMT"
etag: "W/"25-GgaVhntYazB/MPzwqX72WRtisKI""
vary: "Accept-Encoding"
x-powered-by: "Express"
. . . 
SignIn.js:68 false

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

Here is the sign-in page:

import React, { Component } from "react";
import { Redirect } from "react-router";
import { setInStorage } from '../../utils/storage';
import Input from "../../components/Input";
import API from "../../utils/API";
import Header from "../../components/Header";
import Footer from "../../components/Footer";

import "./SignIn.css";


class SignIn extends Component {
  constructor(props) {
      super(props);
      this.state = {
          token: '',
          signInUser: '',
          signInPass: '',
          signInError: '',
          fireRedirect: false
      }

    this.HandleInputChangeSignInPass = this.HandleInputChangeSignInPass.bind(this);
    this.HandleInputChangeSignInUser = this.HandleInputChangeSignInUser.bind(this);
    this.onSignIn = this.onSignIn.bind(this);
  }

  HandleInputChangeSignInUser(event) {
    this.setState({
      signInUser: event.target.value
    });
  }

  HandleInputChangeSignInPass(event) {
    this.setState({
      signInPass: event.target.value
    });
  }

  onSignIn(e) {
    e.preventDefault()
    const {
      signInUser,
      signInPass
    } = this.state

    let siObj = {
      username: signInUser,
      password: signInPass
    }

    API.signIn(siObj)
      .then(json => {
        console.log(json)
        if (json.data.success === true) {
          console.log(json.data.token);
          console.log(json.data);
          setInStorage('the_main-app', { token: json.data.token });
          this.setState({
            signInError: json.data.message,
            isLoading: false,
            signInUser: '',
            signInPass: '',
            token: json.data.token
          });
          this.setState({ fireRedirect: true });
        } else {
          console.log(json.data.success);
          this.setState({
            signInError: json.message,
            isLoading: false
          })
          this.setState({ signInError: true });
        }

      });
  }

  render() {
    const {
      signInUser,
      signInPass,
      fireRedirect
    } = this.state;
      return (
        <div className="signInPage">
          {/* <Container> */}
            <Header/>
            <form className="signIn-form">
                <h3 className="signin-heading"> Hello </h3>
                <Input
                    type="text"
                    placeholder="Username"
                    value={signInUser}
                    onChange={this.HandleInputChangeSignInUser}/>
                <Input
                    type="password"
                    placeholder="Password"
                    value={signInPass}
                    onChange={this.HandleInputChangeSignInPass}/>
                <br />
                <button type="button" className="btn btn-success" id="signin" onClick={this.onSignIn}>Sign In</button>
                <br></br>
                  {
                    this.state.signInError ? <p id="error">Invalid Username or Password</p> : <br/>
                  }
            </form>
            {fireRedirect && (
              <Redirect to={'/profile'} />
            )}
            <Footer />

        {/* </Container> */}
      </div>
    );
  }

}


export default SignIn;

Any suggestions would be greatly welcomed.

Update:

Everything is working now! Yay!!!

Я создаю приложение для создания-реакции.

Я использую существующий API (его написано в MVC С# web api).

API, к которому я хочу использовать приложение React, находится по адресу: https://api.myserver.com.au

Я запускаю версию разработки React из http://localhost

Когда я буду жить, я всегда буду размещать свое приложение React из другого места в API. Т.е. я буду размещать его на https://my.cool.app, и API по-прежнему будет на https://api.myserver.com.au

мой пакет.json выглядит следующим образом:

{
  "name": "hbi.contractor",
  "version": "0.1.0",
  "private": true,
  "proxy": {
    "/api/*": {
      "target": "https://api.myserver.com.au"
    }
  },
  "dependencies": {
    "axios": "^0.17.1",
    "jquery": "^3.2.1",
    "materialize-css": "^0.100.2",
    "nodemon": "^1.14.11",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-form": "^2.16.1",
    "react-live-clock": "^2.0.2",
    "react-load-script": "0.0.6",
    "react-redux": "^5.0.6",
    "react-router-dom": "^4.2.2",
    "react-scripts": "1.0.17",
    "redux": "^3.7.2",
    "redux-thunk": "^2.2.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "react-materialize": "^1.1.2"
  }
}

Когда я устанавливаю прокси-сервер для локального хост-сервера MVC-разработки разработки, он отлично работает, однако, когда на реальном API-сервере и в разработке React, я стараюсь и просматриваю:

http://localhost:3000/api/Acccount/GetUser

и ответ:

Proxy error: Could not proxy request /api/Acccount/GetUser from localhost:3000 to https://api.myserver.com.au (ECONNRESET).

в терминале это очень похоже на это сообщение:

Proxy error: Could not proxy request /api/Acccount/GetUser from localhost:3000 to https://api.myserver.com.au.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).

[HPM] Error occurred while trying to proxy request /api/Acccount/GetUser from localhost:3000 to https://api.myserver.com.au (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors
)

Есть ли способ, по которому я могу перейти к отладке сервера Node (express я take), чтобы я мог получить более подробную информацию об этой ошибке?

У меня есть скрипт открытым, и не похоже, что есть попытка получить доступ к удаленному прокси-серверу.

Является ли функция прокси правильной функциональностью, учитывая, что я планирую сохранить ее таким образом в живой версии?

Любая помощь будет оценена по достоинству.

Есть такое приложение. Установленные модули и зависимости.

Но когда я пытаюсь запустить приложение, API не работает — он пишет ошибку прокси. ( Proxy error: Could not proxy request )

Я перерыл кучу всего в Интернете, есть статья о en.stackover, но, черт возьми, я, кажется, все делаю правильно, но результат тот же. Я не могу понять.

файл package.json

 {  "name": "app",  "version": "0.1.0",  "private": true,  "dependencies": {  "@babel/core": "7.12.3",  "@pmmmwh/react-refresh-webpack-plugin": "0.4.2",  "@svgr/webpack": "5.4.0",  "@testing-library/jest-dom": "^5.11.6",  "@testing-library/react": "^11.2.2",  "@testing-library/user-event": "^12.2.2",  "@typescript-eslint/eslint-plugin": "^4.5.0",  "@typescript-eslint/parser": "^4.5.0",  "babel-eslint": "^10.1.0",  "babel-jest": "^26.6.0",  "babel-loader": "8.1.0",  "babel-plugin-named-asset-import": "^0.3.7",  "babel-preset-react-app": "^10.0.0",  "bfj": "^7.0.2",  "camelcase": "^6.1.0",  "case-sensitive-paths-webpack-plugin": "2.3.0",  "chokidar": "^3.5.2",  "css-loader": "4.3.0",  "datatables.net": "^1.10.23",  "datatables.net-dt": "^1.10.23",  "dotenv": "8.2.0",  "dotenv-expand": "5.1.0",  "eslint": "^7.11.0",  "eslint-config-react-app": "^6.0.0",  "eslint-plugin-flowtype": "^5.2.0",  "eslint-plugin-import": "^2.22.1",  "eslint-plugin-jest": "^24.1.0",  "eslint-plugin-jsx-a11y": "^6.3.1",  "eslint-plugin-react": "^7.21.5",  "eslint-plugin-react-hooks": "^4.2.0",  "eslint-plugin-testing-library": "^3.9.2",  "eslint-webpack-plugin": "^2.1.0",  "express": "^4.17.1",  "file-loader": "6.1.1",  "fs-extra": "^9.0.1",  "html-webpack-plugin": "4.5.0",  "identity-obj-proxy": "3.0.0",  "inputmask": "^5.0.5",  "jest": "26.6.0",  "jest-circus": "26.6.0",  "jest-resolve": "26.6.0",  "jest-watch-typeahead": "0.6.1",  "jquery": "^3.5.1",  "lightbox2": "^2.11.3",  "mini-css-extract-plugin": "0.11.3",  "optimize-css-assets-webpack-plugin": "5.0.4",  "pnp-webpack-plugin": "1.6.4",  "postcss-flexbugs-fixes": "4.2.1",  "postcss-loader": "3.0.0",  "postcss-normalize": "8.0.1",  "postcss-preset-env": "6.7.0",  "postcss-safe-parser": "5.0.2",  "prompts": "2.4.0",  "react": "^17.0.2",  "react-app-polyfill": "^2.0.0",  "react-data-table-component": "^7.0.0-alpha-5",  "react-dev-utils": "^11.0.1",  "react-dom": "^17.0.2",  "react-input-mask": "^2.0.4",  "react-input-range": "^1.3.0",  "react-refresh": "^0.8.3",  "react-router-dom": "^5.2.0",  "resolve": "1.18.1",  "resolve-url-loader": "^3.1.2",  "sass-loader": "8.0.2",  "semver": "7.3.2",  "slick-carousel": "^1.8.1",  "style-loader": "1.3.0",  "styled-components": "^5.3.0",  "terser-webpack-plugin": "4.2.3",  "ts-pnp": "1.2.0",  "url-loader": "4.1.1",  "webpack": "4.44.2",  "webpack-dev-server": "3.11.0",  "webpack-manifest-plugin": "2.2.0",  "workbox-webpack-plugin": "5.1.4"  },  "scripts": {  "start": "node --max-http-header-size=14120024 --max-old-space-size=20096 scripts/start.js",  "build": "node scripts/build.js",  "test": "node scripts/test.js"  },  "eslintConfig": {  "extends": [  "react-app",  "react-app/jest"  ]  },  "browserslist": {  "production": [  "gt;0.2%",  "not dead",  "not op_mini all"  ],  "development": [  "last 1 chrome version",  "last 1 firefox version",  "last 1 safari version"  ]  },  "proxy": "http://localhost:3000/",  "jest": {  "roots": [  "lt;rootDirgt;/src"  ],  "collectCoverageFrom": [  "src/**/*.{js,jsx,ts,tsx}",  "!src/**/*.d.ts"  ],  "setupFiles": [  "react-app-polyfill/jsdom"  ],  "setupFilesAfterEnv": [],  "testMatch": [  "lt;rootDirgt;/src/**/__tests__/**/*.{js,jsx,ts,tsx}",  "lt;rootDirgt;/src/**/*.{spec,test}.{js,jsx,ts,tsx}"  ],  "testEnvironment": "jsdom",  "testRunner": "/Users/user/Downloads/goroskop2/node_modules/jest-circus/runner.js",  "transform": {  "^. .(js|jsx|mjs|cjs|ts|tsx)$": "lt;rootDirgt;/node_modules/babel-jest",  "^. .css$": "lt;rootDirgt;/config/jest/cssTransform.js",  "^(?!.*.(js|jsx|mjs|cjs|ts|tsx|css|json)$)": "lt;rootDirgt;/config/jest/fileTransform.js"  },  "transformIgnorePatterns": [  "[/\]node_modules[/\]. .(js|jsx|mjs|cjs|ts|tsx)$",  "^. .module.(css|sass|scss)$"  ],  "modulePaths": [],  "moduleNameMapper": {  "^react-native$": "react-native-web",  "^. .module.(css|sass|scss)$": "identity-obj-proxy"  },  "moduleFileExtensions": [  "web.js",  "js",  "web.ts",  "ts",  "web.tsx",  "tsx",  "json",  "web.jsx",  "jsx",  "node"  ],  "watchPlugins": [  "jest-watch-typeahead/filename",  "jest-watch-typeahead/testname"  ],  "resetMocks": true  },  "babel": {  "presets": [  "react-app"  ]  } }  

Структура проекта:
-api
-конфигурация
-node_модули
-публичные
-сценарии
-src
-загрузить
-пакет поставщика

.пакет json-блокировка.json

Если бы кто-нибудь мог подсказать, я был бы чрезвычайно благодарен.

Что я пробовал:
Поставил прокси
http: // локальный
хост http: // локальный хост /
http: // локальный хост: 3000
http: // локальный хост: 3000 /

Запустите сборку serve -s.

В этом случае он работает на порту 3000, и при запуске приложения при доступе через API он выдает html-страницу (из каталога сборки).

Я также пытался запускать сценарии узлов / start.js и npm начинаются отдельно.
Как и планировалось — вышла ерунда, но я уже все перепробовал.

Понравилась статья? Поделить с друзьями:
  • Proxy error cannot connect to proxy
  • Proxy connect error соединение закрыто пиром
  • Proxy connect error отключен превышено время ожидания
  • Proxy 10060 error
  • Prototype 1 как изменить расширение экрана