static.json not working for ReactJS routes and Heroku

自作多情 提交于 2019-12-24 22:05:24

问题


In theory this should work, adding at the / folder the file /static.json that makes everything go to the React index.html.

(related)

React Routing works in local machine but not Heroku

https://github.com/heroku/heroku-buildpack-static#configuration

In my case it doesn't work, I get a Cannot GET /hello instead of receiving the index.html. Surprisingly, if I go directly to /index.html I get the page but no route is activated.

What is happening and how can I fix it?

UPDATE: tried without luck /static.jason /src/static.jason /client/static.jason /client/src/static.jason

/static.json

{
  "routes": {
    "/**": "index.html"
  }
}

/client/src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import FileUpload from './FileUpload';

ReactDOM.render(
  <div><FileUpload /></div>,
  document.getElementById('root')
);

/client/src/FileUpload.mjs

import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';

class TextFileReader extends Component {
 render() {
  return (
   <Router>
    <div>
     <Route path="/heyyo" render={() => <span>heyyo</span>} />
     <Route exact path="/" render={() => <div>resting</div>} />
     <Route path="/what" render={() => <div>what</div>} />
      NO ROUTES HERE
    </div>
   </Router>
  )
 }
}

export default TextFileReader;

回答1:


Finally, re-reading better this React Routing works in local machine but not Heroku I've added this line to my Express

app.get('/*', (req, res) => {
  let url = path.join(__dirname, '../client/build', 'index.html');
  if (!url.startsWith('/app/')) // we're on local windows
    url = url.substring(1);
  res.sendFile(url);
});

And once deployed to Heroku, it works :)



来源:https://stackoverflow.com/questions/52852877/static-json-not-working-for-reactjs-routes-and-heroku

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!