簡體   English   中英

setupProxy 不工作 - http-proxy-middleware

[英]setupProxy is not working - http-proxy-middleware

我的反應應用程序在 localhost:3000 上運行,節點服務器在 localhost:5000 上運行。 當我嘗試連接到 express API 時,路由將轉到 'localhost:3000/auth/google' 而不是 localhost:5000/auth/google

我在嘗試使用 express api 時遇到的錯誤

用戶操作.js

export const updateLoginUser = (userData, scheme) => async dispatch => {
console.log(scheme);
if(scheme === 'google') {
    // TODO: fetch user from the DB
    const fetchedUser = await axios.post('/auth/google');
    dispatch({
        type: UPDATE_USER, 
        payload: fetchedUser.data
    })
} else {
    // TODO: fetch user from the DB
    const fetchedUser = await axios.post('/api/get_user/', {
        method: 'POST',
        headers: {
            'content-type': 'application/json'
        },
        body: JSON.stringify(userData)
    })
    dispatch({
        type: UPDATE_USER, 
        payload: fetchedUser.data
    })
}

}

setupProxy.js

 const proxy = require('http-proxy-middleware')
module.exports = function(app) {
    app.use(proxy('/auth/google', { target: 'http://localhost:5000' }))
}

節點服務器.js

const express = require('express');
const mongoose = require('mongoose');
const keys = require('./config/keys');
const cookieSession = require('cookie-session');
const passport = require('passport');
const cors = require('cors');
const morgan = require('morgan');

require('./models/Users');
require('./services/passport'); // it is not returing anything hence no need of assigning

mongoose.connect(keys.mongoDBURI, { useNewUrlParser: true, useUnifiedTopology: true });

const app = express();
app.use(cors());

// Setup the cookie session
app.use(cookieSession({
    maxAge: 30 * 24 * 60 * 1000, // Time till the cookie will be alive
    keys: [keys.cookieKey]
}));


app.use(morgan('combined'));
// Make passport know to use the cookieSession
app.use(passport.initialize());
app.use(passport.session());

require('./routes/authRoutes')(app); // authRoute returing a function and we are immediatly invoking that function

const PORT = process.env.PORT || 5000;
app.listen(5000);

編輯:反應 package.json

{
  "name": "blogpost-frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.19.0",
    "http-proxy-middleware": "^0.20.0",
    "node-sass": "^4.13.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-redux": "^7.1.3",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.2.0",
    "redux": "^4.0.4",
    "redux-thunk": "^2.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:5000"
}

我是新手,因此我不知道代理的工作原理。

你可能需要重寫你的 setupProxy.js 如下

 const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function(app) { app.use( '/api', createProxyMiddleware({ target: 'http://localhost:5000', changeOrigin: true, }) ); };

然后進行 npm 安裝。

在我的情況下,解決了這個問題。 在這里你可以看到更多細節https://create-react-app.dev/docs/proxying-api-requests-in-development/還有它被提到注意:這個文件只支持 Node 的 JavaScript 語法。 確保只使用受支持的語言功能(即不支持 Flow、ES 模塊等)。

這樣做的方法是在 app.get('/what-here', ....) 中使用你在 express 中使用的路由你也在 setupProxy.js 中使用 function (app){ app.use('/ what-here', createproxyMiddleware({ target: URL, change origin:true})。what-here 附加到 URL,並且 URL 代理到客戶端應用程序使用的前端 URL。也就是說,如果客戶端位於localhost:3000 ant 服務器在 localhost:5000 請求然后在 localhost:5000/what-here 但它顯示為 localhost:3000/what-here 給客戶端。錯誤是在 express 然后使用不同的名稱setupProxy

我有同樣的問題。 問題不是 setupProxy.js,問題是 axios 發布的路徑在后端不存在。 這可能是由后端路由中的拼寫錯誤引起的。
確保后端路由路徑與前端 post 路徑相同。
首先確保您的 setupProxy.js 看起來像這樣:

const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:5000',
      changeOrigin: true,
    })
  );
};

axios.post 以 /api 開頭,我的是:

await axios.post("/api/conversion/convert", data);

我正在使用 axios.post('/api/conversion/convert') 發布,但我的快遞后端有一個發布路線 'api/convertion/convert' 這是我的錯字(轉換而不是轉換),它使 axios 發布到3000 而不是 5000。
我不知道這是一個什么樣的錯誤, axios 發布到 3000 而不是 5000 因為后端路由不匹配。 預期的行為是它應該發布到 5000/wrong-post-path 以便於調試。

PS如果這解決了您的問題,請點贊。 我是回答問題的新手,贊成票真的會增加我的帳戶。

我認為您忘記添加app.listen(api, proxy())的第一部分並且您只有proxy方法,問題可能是您沒有指定要通過代理的 url/路徑。

var express = require('express');
var proxy = require('http-proxy-middleware');

var app = express();

app.use(
  '/api', // you miss this part in your server code
  proxy({ target: 'http://www.example.org', changeOrigin: true })
);
app.listen(3000);

// http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM