Let's imagine i have a express server from where i can send react app file on browser request - app.js
fastify.route({
method: 'GET',
url: '/index.html',
handler: (req, res) => {
res.sendFile(app.js)
}
})
On client side i want browser to accept it as index.html with react inside.
import React from 'react'
import { render } from 'react-dom'
import App from './src/App'
// Where to place all html?
render(<App />, document.getElementById('someid'))
To put it simple, i want to get rid of index.html and generate it dynamically.
How can i do it?
Your react app is just a JavaScript bundle where as browser can only understand Html and execute js.
Browser parses HTML and creates DOM tree, during this process it fetches all the JavaScript in script tags. And React is not HTML.
So you have to send index.html for that matter any html file is must be sent to the browser first.
Related
I would like to server-side render only a specific route in React. For example, /home should be client-side rendered, but /post should be server-side rendered.
The /post route receives a post ID as a parameter(using react-router) and fetches the content from a database server.
Is their any way I can server-side render only a specific page/route using react-dom server?
Your data should be handled by the middleware and stored there to minimize api calls. The Front end should render based on that data.
One good approach is to use built version of your react within express.js server. So let's say you have your built version of your react inside build directory :
var express = require('express');
var app = express();
app.use("/post",function(req,res) {
console.log(req); // Do your stuff for post route
});
app.use("/",express.static(path.join(__dirname,"/build")));
app.use("/*",express.static(path.join(__dirname,"/build"))); // Handle react-router
const httpServer = require("http").createServer(app);
httpServer.listen(8080, function(){
console.log("Server is running on 8080");
});
How do I set the routes for my React Single page application in Express js
Navigate a React App link from a single page application to Express server dynamically
Your question is not completely clear but I'm assuming you want to know how to use express for API routes and still server react on the frontend. If this is the case you can do it like this on your backend file (let's call it server.js). And the react app is in a folder called "client":
const app = express();
// API routes
app.get("/api/test", (req, res) => {
res.send('example response from backend');
});
// If no API routes are hit, send the React app
app.use(function (req: Request, res: Response) {
res.sendFile(join(__dirname, "./client/build/index.html"));
});
Note that you have to send the React app last. This line must come after all other routes.
I'm following this tutorial to make my React app (localhost:3000) communicate with Node server (localhost:5000) .. so instead of typing <Link to='localhost:5000/auth/google'>Login with Google</Link> I only want it to be just '/auth/google', but when I click on the button with Link tag it sends this error "No routes matched location "/auth/google"
I'm using React v17.0.2
this is what's inside my setupProxy.js file
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
["/auth/google", /api/*],
createProxyMiddleware({
target: "http://localhost:5000",
changeOrigin: true,
})
);
};
the weird thing though is that I got no error when I type the route directly in the browser (both ports work just fine) and it redirect me to the page I want (handled by Express)
If there's no solution for this problem for now, is there any other way to use a proxy in a MERN application because from what I know adding "proxy" in package.json is not working anymore
I am working on a NextJS project, and I need a form loaded on server, to be able to upload files so for that I used multer along with express in a custom server.
Now on GET request I want to render a specific page, but I am not sure how I can do this. I don't want to have any html in the server, just a call to the page. Is this even possible?
server.get('/', (req,res) => {
res.send(ReactDOMServer.renderToString(<myPage />))
});
when I start the server I am getting the following:
/Users/MONOLITH-Strat-Audrey/Projects/sandbox/multer-file-upload/server.js:41
res.send(ReactDOMServer.renderToString(<myPage />))
^
SyntaxError: Unexpected token <
In the server I am calling the page like this, which obviously doesn't work.
const myPage = require('./pages/index')
For references, this is my github with all the code.
Github Repo
There is a multipart error in your code.
Never import React components in server.js or node entry point file.
All pages should reside inside pages directory for Next.js to
parse it and serve.
Below are the changes made and it started working
Remove or comment below line from server.js
const myPage = require('./pages/index')
In line 48 - server.js
server.get('/',function(req,res){
// res.write(ReactDOMServer.renderToString(<myPage />))
return app.render(req, res, '/', query)
});
In your components/file.js render method return the jsx
class File extends Component {
render() {
return (<form action="/uploadfile" enctype="multipart/form-data" method="POST">
<input type="file" name="myFile" />
<input type="submit" value="Upload a file"/>
</form>)
}
}
References for custom server using Next.js
SSR in Next.js -
https://nextjs.org/docs/basic-features/pages#two-forms-of-pre-rendering
Next.js Custom server -
https://nextjs.org/docs/advanced-features/custom-server
Custom server example -
https://github.com/zeit/next.js/tree/canary/examples/custom-server
I have several components displayed with react router that have dynamic url paths. An example path I have is
<Route path="/newproject/:id" onEnter={checkSesh} component= {ProjectDetails} />
When entering this component, I have a componentWillMount function that extract the id part of the url so that I can get the info for the correct project and render it on the ProjectDetails component.
componentWillMount() {
var id = this.props.router.params.id
this.props.teamDetails(id);
}
this.props.teamDetails(id) this calls a redux action creator that will make an axios request to an express route that will get the project info from the database.
export function teamDetails(id) {
return function(dispatch) {
axios.get('/getteaminfo/' + id)
.then(res => {
dispatch({ type: "SET_TEAM_DETAILS", payload: {
teamInfo: res.data.teamInfo,
admin: res.data.admin,
adminID: res.data.teamInfo.teamAdmin,
teamMembers: res.data.teamInfo.teamMembers
}
})
});
}
}
everything works fine upon visiting the page after already being logged in etc. But when I refresh the page /newproject/:id, i get an error Uncaught SyntaxError: Unexpected token <. An example url in my browser looks like http://localhost:3000/newproject/58df1ae6aabc4916206fdaae. When I refresh this page, I get that error. The error is complaining about my <!DOCTYPE html> tag at the very top of my index.html for some reason. This index.html is where all of React is being rendered.
When page is refreshed store state is not preserved. Make sure the state is not important to load the page, or at least initialized properly every time.
For e.g. login information if saved in store and not on browser with localStorage or cookies etc.. then on refresh, the error will come when trying to access /getteaminfo/ route through axios. The response will have error html and it can't be parsed by js.
Please check your web console on for more information. You can use chrome extension like https://github.com/zalmoxisus/redux-devtools-extension which will show your store and etc..
Make sure to check what /getteaminfo/ gives with id is not passed.
Also, make sure on your server side, did you route requests to react-router path through something like this?
e.g. express js,
app.get('*', function response(req, res) {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
be sure to sendFile with the real location of index.html
I found the answer here: react-router dynamic segments crash when accessed I added <base href="/" /> into the <head>of my index.html. You can also read more info here: Unexpected token < error in react router component