如何配置Nginx React和Express

gt0wga4j  于 2023-03-29  发布在  Nginx
关注(0)|答案(1)|浏览(207)

我在GCP ubuntu 22 vm上使用React和express配置Nginx时遇到了一些问题。我有一个防火墙,并为API服务器(express)启用了Nginx Full和端口3005。尽管react应用程序正在正确服务,但我一直从api请求中获得404未找到响应。
以下是用于测试目的的简单react应用程序:

import './App.css';
import { useState } from 'react';

const API_BASE = 'http://mydomain/api/'

function App() {

  const [currentResponse, setCurrentResponse] = useState(null)

  const makeReqeustToAPI = (route) => {
    return fetch(`${API_BASE}${route}`)
      .then(response => response.json())
      .then(data => {
        console.log(data)
        setCurrentResponse(data)
        
      })
      .catch(err => console.log(err)) 
  }

  return (
    <div className="App">
      <h1>Hello world, I'm a react app...</h1>

      <div className="button-container">
        <button className='btn' onClick={() => {
          makeReqeustToAPI('')
        }}>api home route</button>
        <button className='btn' onClick={() => {
          makeReqeustToAPI('products')
        }}>api products route</button>
        <button className='btn' onClick={() => {
          makeReqeustToAPI('products/3')
        }}>api products specific route</button>
      </div>

      {currentResponse && <div>{Object.keys(currentResponse).map((key, index) =>{ 
        const item = currentResponse[key]
        if(typeof item === 'object') {
          return <h2 key={index}>{`${key}: ${currentResponse[key].value}`}</h2>
        } else {
          return <h2 key={index}>{`${key}: ${currentResponse[key]}`}</h2>
        }
      })}</div>}
      
    </div>
  );
}

export default App;

以下是Express App:

const express = require('express')
const app = express()
const cors = require('cors')

const products = {
    product1: {
        id: 1,
        value: 'apple'
    },
    product2: {
        id: 2,
        value: 'bannana'
    },
    product3: {
        id: 3,
        value: 'salt'
    },
    product4: {
        id: 4,
        value: 'yogurt'
    }
}

app.use(express.json())
app.use(cors())

app.get('/', (req, res) => {
    res.json({greeting: 'hello world', type: 'I\'m an express response'})
})

app.get('/products', (req, res) => {
    res.json({product1: products.product1, product2: products.product2, product3: products.product3, product4: products.product4})
})

app.get('/products/:id', (req, res) => {
    const id = Number(req.params.id)
    const item = Object.keys(products).map(key => products[key]).find(product => product.id===id)
    if(1<2) {
        res.json({item: products.product1})
    } else {
        res.status(404).send('not found')
    }
    
})

const PORT = 3005
app.listen(PORT, () => {
    console.log(`App listening on port ${PORT}`)
})

nginx配置:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        proxy_pass http://localhost:8080;
    }

    location /api {
        proxy_pass http://localhost:3005;
    }

}
ih99xse1

ih99xse11#

当你点击/API端点时,nginx会将请求路由到localhost:3005/api而不是localhost:3005。为了解决这个问题,你需要添加一个rewrite指令:

# Rewrite requests to the Node.js server
location /api {
  rewrite ^/api(.*)$ $1 break;
  proxy_pass http://localhost:3005/;
}

相关问题