React App代理错误:无法代理请求

时间:2018-08-14 03:46:19

标签: reactjs proxy

我正在研究已部署在Heroku上的小组项目,但是现在我需要对其进行进一步的工作,并试图使其再次在本地运行。这是一个使用MongoDB的React应用。我克隆了仓库,并在根文件夹和客户端文件夹中都安装了npm。当我输入npm run dev时,页面出现,但是功能不起作用。尝试登录,注册或提交照片时出现错误:

从终端:

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

从控制台:

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)

我查看了错误日志,似乎服务器拒绝建立连接。我不知道是什么问题。最让我感到困惑的是,我的另一个团队成员也克隆了该回购协议,并声称一切对他都有效。在Heroku上部署时,它也可以正常工作。我的计算机上是否有可能引起问题的特定设置?我的防火墙已关闭。如果代码有问题,请参考以下内容:

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

我非常感谢您提供解决此问题的建议。我已经为此工作了好几天,无法使其正常工作。我对编码非常陌生-对React还是陌生的-我感到非常沮丧。 预先谢谢你。

更新 感谢您的快速回复!浏览完文件后,我意识到我没有.env文件,因此没有Watson api或AWS的密钥。我添加了一个,代理错误消失了。但是现在我仍然有其他错误。

在应用程序中,填写注册表单,然后将您带到登录页面。我将我的名称和密码添加到了注册页面,但是我认为它不会吸收信息。当我尝试登录时,我的名称和/或密码显然无效。 (模型中对密码的唯一限制是密码必须是6个字符。)当我尝试登录时,在控制台中看到以下内容:

{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

现在我想知道这是否是数据库的问题。

这是登录页面:

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;

任何建议都会受到欢迎。

更新

现在一切正常!是的!

2 个答案:

答案 0 :(得分:0)

在package.json文件中添加“ proxy”:“ http://0.0.0.0:3001”  “ main”:“ server.js”,

答案 1 :(得分:0)

  1. 你可以在package.JSON中的"secure": false之后添加"proxy": "http://0.0.0.0:3001",例如:
 "proxy": {
    "/api": {
      "target": "http://0.0.0.0:3001",
      "secure": false
    }
  },

它对我有用

  1. 你可以使用http-proxy-middleware