Next.js stylesheet is not loaded - html

I'm using Next.js to build my website. I modify the server using express.js server so I have server.js on my root folder of my project.
When I started the server npm run dev which run node server.js, my home page renders correctly. But when I navigate to some of other page in my website, the css is not loaded. But if I refresh the page, it will load the css and the problem is gone
const express = require('express')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const app = next({dev})
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
server.get('*', (req, res) => {
return handle(req, res)
})
const port = process.env.PORT || 3000
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on port ${port}...`)
})
})
Here's my server.js file. I think there is no problem with the code.
I use #zeit/next-less package for compiling my LESS stylesheet
Please help
Thanks

Check this out: https://github.com/zeit/next-plugins/issues/282
In short as a workaround:
Create an empty CSS file in /static/ directory.
Import it in _app.js:
import '../static/jank-empty.css';
I hope that it would help.

For me the issue was that the nextjs wasn't loading the rel=stylesheet link tags. It was only able to load rel=preload link tags.
so I did a workaround like this:
document.querySelectorAll("link[rel='preload'][as='style']").forEach(link => link.rel = "stylesheet")

Related

Showing HTML file in Node js Application

I am new on Node.js and I have app.js file like:
const express = require('express');
const app = express();
const port = 8080;
app.get('/', (req, res) => res.send('Hello World'));
app.listen(port);
console.log(`App running on http://localhost:${port}`);
I also have index.html file in the same folder with app.js. Here there is a HTML5 website.
When I run the project I can see Hello World text in browser, How can I show this HTML file from my app.js so when I deploy it, it should show me responsive HTML file instead of Hello World?
I tried
app.get('/',function(req,res) {
res.sendFile('index.html');
});
But didn't see a difference.
To make your code example work you'll need to specify an absolute path, try using this:
res.sendFile(__dirname + "/index.html");
Another way would be to use EJS (https://ejs.co/)
In your example, you could do the following:
Install EJS:
npm install ejs
Set the View Engine to EJS:
app.set('view engine', 'ejs')
- Move your index.html file to a folder called "views" and also rename the file to index.ejs
views/index.ejs
In your app.get() handler, use:
res.render('index')
Final Result:
const express = require("express");
const app = express();
app.set("view engine", "ejs");
const port = 8080;
app.get("/", (req, res) => {
res.render("index");
});
app.listen(port, () => {
console.log(`App running on http://localhost:${port}`);
});
(note: I also moved your console.log to inside app.listen)
I found this on another stack overflow question, it should work
fs.readFile(__dirname + '/views/test.html', 'utf8', function(err, text){
res.send(text);
});

How do 'no code' websites publish webpages for each user? [duplicate]

I am used to working on httpd ( Apache ) which provides a way to configure subdomains which is mapped to a directory.
How can I do the same thing in Connect.js/Express.js ? I see that the only thing that I have is routes which I am not sure how I can use to configure sub domains. I have subdomains like m.mysite.com, sync.mysite.com
Can someone help ?
Or alternatively you could use vhost.
Then, create several sites in their own directory and export the express app, eg. /path/to/m/index.js:
var app = express()
/* whatever configuration code */
exports.app = app
// There is no need for .listen()
And then handle all requests with the following app:
var vhost = require('vhost');
express()
.use(vhost('m.mysite.com', require('/path/to/m').app))
.use(vhost('sync.mysite.com', require('/path/to/sync').app))
.listen(80)
Note that /path/to/m and /path/to/sync can be absolute paths (as written above) or relative paths.
You could append a subdomain to a request and then check for it in subsequent next() calls.
I got the following code from > http://groups.google.com/group/express-js/browse_thread/thread/b04bbaea7f0e8eed (so full credit to the original author)
app.get('*', function(req, res, next){
if(req.headers.host == 'some.sub.domain.com') //if it's a sub-domain
req.url = '/mysubdomain' + req.url; //append some text yourself
next();
});
// This will mean that all get requests that come from the subdomain will get
// /subdomain appended to them, so then you can have routes like this
app.get('/blogposts', function(){
// for non-subdomain
});
app.get('/mysubdomain/blogposts', function(){
// for subdomain
});
I have recently came across this problem, and wrote a module to help with it using express 4. https://www.npmjs.org/package/express-subdomain.
Example - api subdomain.
var express = require('express');
var app = express();
var router = express.Router();
//api specific routes
router.get('/', function(req, res) {
res.send('Welcome to our API!');
});
router.get('/users', function(req, res) {
res.json([
{ name: "Brian" }
]);
});
app.use(subdomain('api', router));
app.listen(3000);
Check out the module on npm to see more examples.
I created a module to help with subdomains in Express: https://github.com/WilsonPage/express-subdomain-handler
Do as I say, create two express app in different folder.
For example:
one app in /blogsite directory
const express = require("express");
const blog = express();
blog.get("/", (req, res) => {
res.send("BLOG SECTION");
});
blog.get("/allblogs", (req, res) => {
res.json([
{ title: "csgo major boston", description: "Best CSGO major ever" },
{ title: "Blast pro series", description: "Coolest series of CSGO" },
]);
});
module.exports = { blog };
and another one in /portfolio directory
const express = require("express");
const portfolio = express();
portfolio.get("/", (req, res) => {
res.send("PORTFOLIO SECTION");
});
portfolio.get("/resume", (req, res) => {
res.send("HERE'S MY RESUME");
});
module.exports = { portfolio };
Now create a main app in the outer folder and import the other two express apps that you just made in /blogsite directory and /portfolio directory.
And in the main app do this,
const express = require("express");
const vhost = require("vhost");
const { blog } = require("./blogsite");
const { portfolio } = require("./portfolio");
const app = express();
// BLOG AND PORTFOLIO
// url: http://blog.localhost:3002/
// url: http://blog.localhost:3002/allblogs
// url: http://portfolio.localhost:3002/
// url: http://portfolio.localhost:3002/resume
app
.use(vhost("portfolio.localhost", portfolio))
.use(vhost("blog.localhost", blog));
// MAIN APP ROUTES OR ENDPOINTS
// url: http://localhost:3002
// url: http://localhost:3002/myhobbies
app.get("/", (req, res) => {
res.send("MAIN APP SECTION");
});
app.get("/myhobbies", (req, res) => {
res.send("MAIN APP -> myhobbies section");
});
app.listen(3002, () => {
console.log("started listening");
});
fileStructure at the end should be looking like this
main(folder)
index.js (main express app which you need to run using node or nodemon)
blogsite(folder that I talked about for blog.localhost)
index.js (blog express app)
portfolio(folder)
index.js (portfolio express app)
I've had this exact same requirement for a project I was working on and ended up throwing together a middleware-based solution. It allows you to define routers and view folders per subdomains.
Check it out on NPM https://www.npmjs.com/package/express-multiview
or GitHub https://github.com/daryl-cecile/express-multi-view#readme

Return HTML file using Adonisjs Router

I am creating one web application using AdonisJs in backend and ReactJs in frontend.
While integrating both frameworks i am struggling to return index.html file of ReactJs on '/' route path from AdonisJs, since AdonisJs is supporting edge.js for view.
Is there any solution in AdonisJs similar to expressjs returning HTML file as given below
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(9000);
Currently my AdonisJs route returning edge file like,
Route.any('*', ({view}) => view.render('index'))
You can change template file extensions in config file which resides on config/app.js.
{
static: {
extensions: ['html']
}
}
For this you need to be running Adonis by motorcycle stack, if using only as API it will only return JSON rendered responses
now if you are in an Adonis stack installation just use the view object that looks like this:
Route.get('/page', ({ view }) => {
view.render('name_of_view')
})

GET to CSS returns 404

So I recently moved my website from a single-page website to an express server. Now I changed the file paths, but I cannot get my css and js files to load.
As seen in the developer console, the GET request to https://<website>.com/public/css/main.css returns a 404.
This is the css link:
<link rel="stylesheet" type="text/css" href="../public/css/main.css">
This is my server:
const express = require('express');
const app = express();
const getpages = require('./router/getpages.js');
app.use('/', getpages);
app.use(express.static('public'));
// 404's
app.use((req, res) => {
res.status(404).send('Page not found or non-existant.<br><br>Home');
});
app.listen(3000, console.log('Running on port 3000'));
This is ./router/getpages.js:
const router = require('express').Router();
const path = require('path');
router.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../views/', 'index.html'));
})
module.exports = router;
This is the file structure:
Note, I could not find any other questions that helped me, before this is marked as a dupe again.
As can be seen from the documentation, you should not have public in the route
https://<website>.com/css/main.css should work as expected.
refer : https://expressjs.com/en/starter/static-files.html
For example, use the following code to serve images, CSS files, and
JavaScript files in a directory named public:
app.use(express.static('public'))
Now, you can load the files that are
in the public directory:
eg : http://localhost:3000/images/kitten.jpg
Express looks up the files relative to the static directory, so the
name of the static directory is not part of the URL.

How to send React.js files with express .senfFile?

I am using create-react-app.
When you go to localhost:3001/test - it does serve up the HTML. But all you see is an empty page because nothing in the id "root" is rendered.
This is the code I have in my server:
app.get('/test', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
})
and my HTML is close to this:
<body>
<div id="root"></div>
</body>
You have to set the location of the static files. For example if you use environment variable.
if(process.env.ENV === 'prod'){
app.use(express.static('client/build'));
const path = require('path');
app.get('/test', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
})
}
Also, do make sure to run npm run build in order to create all the necessary files for deployment.
Based on the few details provided, I'll give a checklist
1- Make sure you have root in this part of your code
ReactDOM.render(<YourApp />, document.getElementById('root'));
2- In your console, do you have any error messages similar to this?
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
...Then your are just simply not receiving your data from the server because of CORS issues. Use this: CORS
3- Double check that your server that does the res.sendFile is running properly, check your terminal to check for errors like "file not found" or similar issues.
4- This works (I just tried it), try it in the same directory as your current server. Paste the code in testNode.js and run node testNode.js then visit http://localhost:3003/test
const express = require('express')
const app = express()
const port = 3003
app.get('/test', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
})
app.get('/', (request, response) => {
response.send('Hello from Express!')
})
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
5- Is the public/ folder readable? Does it have the right permissions? Try a chmod -R 777 public/ (change it back later)