簡體   English   中英

Express.js路由404

[英]Express.js routing 404

我在我的React應用程序中使用express.js動態路由存在問題。 一切都可以在localhost上運行,但是當我部署時我得到400。這是鏈接: https : //shoppyshop.herokuapp.com/item/1

如您在控制台中看到的,有400錯誤。 我的目標是從我在Express的index.js中設置的路由中正確獲取數據。

app.get('/api/item/:id', function (req, res) {
    let find = data.filter((el => {
        return el.product.id == req.params.id
    }))
    res.json(find)
    console.log('found item')
})

我了解快遞有問題。 我可能使用了錯誤的方法,因此它想從錯誤的路徑獲取圖標並保存文件。 正在谷歌搜索,找不到類似的問題。 如何解決? 這是獲取數據的組件:

export default class ItemInfo extends Component {
    constructor(props) {
      super(props)

      this.state = {
         data: []
      }
    }

    componentDidMount = () => {
        axios.get(`/api/item/${this.props.match.params.id}`)
            .then(res => {
                const data = res.data;
                this.setState({
                    data,
                    fetched: true
                })
            })
    }

  render() {
      console.log(this.props.match.params.id)
    return (
      <div className="App">
      <SideBar pageWrapId={"mainpage"} outerContainerId={"MainPage"} />
      <div id="mainpage">
          <TopBar />
          <More data={this.state.data} fetched={this.state.fetched}/>
          <Footer />            
      </div>
  </div>
    )
  }
}

這是我正在處理的代碼的分支: https : //github.com/KamilStaszewski/shoppy/tree/itemrouting/client

我的express.js文件:

const express = require('express');
const path = require('path');
const data = require('./apiData');

const app = express();

// Serve the static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));
app.disable('etag');


app.get('/category/:category', function (req, res) {
    let find = data.filter((el => {
        return el.product.category == req.params.category
    }));
    res.json(find);
    console.log('found category');
});

app.get('/api/item/:id', function (req, res) {
    let find = data.filter((el => {
        return el.product.id == req.params.id
    }))
    res.json(find)
    console.log('found item')
})

// An api endpoint that returns a short list of items
app.get('/api/data', (req, res) => {
    var questions = data
    res.json(questions);
    console.log('Sent list of items');

});




// Handles any requests that don't match the ones above
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname + '/client/public/index.html'));
});

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

console.log('App is listening on port ' + port);

更新:

經過多次提交和推送,我找到了答案。 我不知道它的正確方法,但是它有效。 問題在於:

app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname + '/client/public/index.html'));
});

我不是從build提供索引,而是從public那里提供索引,其中沒有js。 為了使它起作用,我更改為:

app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname + '/client/build/index.html'));
});

現在可以了。

我很確定這是您如何在Express中提供靜態文件的問題。

從快速文檔:

app.use('/ static',express.static('public'))

現在,您可以從/ static路徑前綴加載公共目錄中的文件。

http:// localhost:3000 / static / images / kitten.jpg

http:// localhost:3000 / static / css / style.css

http:// localhost:3000 / static / js / app.js

http:// localhost:3000 / static / images / bg.png

http:// localhost:3000 / static / hello.html

但是,您提供給express.static函數的路徑是相對於您啟動節點進程的目錄的。 如果從另一個目錄運行express app,則使用要提供服務的目錄的絕對路徑更為安全:

app.use('/ static',express.static(path.join(__ dirname,'public')))

您的代碼具有以下服務靜態代碼:

app.use(express.static(path.join(__dirname, 'client/build')));

因此,如果我在閱讀您的代碼時正確閱讀了以下內容,我將理解為:

當您收到/的請求時,其余的調用將在client/build搜索數據。 在您的情況下,對於/api/item/:id get請求,服務器可能會讀取該請求,以嘗試在client/build/api/item/:whatevertheitemidis找到一個靜態文件。

相反,要提供靜態文件,我可能會考慮將其放置在名為“ public”之類的目錄中,然后將您的提供靜態文件更改為以下內容:

app.use('/public', express.static(path.join(//Wherever you keep your static files)));


綜上所述,我可能對express.static某些細微差別有誤,所以請務必查看文檔 無論哪種方式,我都希望至少已為您指明了正確的方向。 如果您注釋掉服務靜態行並向郵遞員提出請求,則應該看到它可以正常工作。


更新

我看了看您的代碼,發現以下幾點:

  1. 我只是拉下您的代碼,端點正常工作。 我嘗試了http://localhost:5000/api/data ,它提供了預期的數據。

  2. 您提供靜態資產(例如您的%PUBLIC_URL%/圖標)的問題似乎是由於html中%PUBLIC_URL%/圖標網址的%PUBLIC_URL%/部分引起的。 據我所知,您的代碼中沒有任何東西可以將其轉換為實際路線。 一旦我將其轉換為/favicon ,一切就會按預期開始工作。

暫無
暫無

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

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