Heroku working differently than running locally - javascript

I created a Nuxt app with express backend, and i have registered some api routes. When i run locally as production npm run build && npm run start it works just fine.
Here it is working locally
However when i run it with heroku heroku local web all the API routes throw a 404.
Here it doesn't work with heroku
Here is my server code
require('dotenv').config();
const express = require('express');
const consola = require('consola');
const { Nuxt, Builder } = require('nuxt');
const bodyParser = require('body-parser');
const session = require('express-session');
const mongoose = require('mongoose');
const cors = require('cors');
mongoose.Promise = Promise;
mongoose.set('useFindAndModify', false);
mongoose.connect(process.env.MONGODB_CONNECTION_STRING);
const app = express();
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js');
config.dev = process.env.NODE_ENV !== 'production';
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config);
const { host, port } = nuxt.options.server;
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt);
await builder.build();
} else {
await nuxt.ready();
}
app.use('/api', require('./routes'));
// session
app.use(
session({
sessionDataHere
})
);
// enable cors
app.use(cors());
// body parser
app.use(bodyParser.json());
app.use((error, req, res, next) => {
console.error(error.response);
res.status(500).send(error);
});
// Give nuxt middleware to express
app.use(nuxt.render);
// Listen the server
app.listen(port, host);
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
});
}
start();
And here is the index of my routes
const { Router } = require('express');
const authRouter = require('./auth');
const videoRouter = require('./video');
const baseRouter = Router();
baseRouter.use('/', authRouter);
baseRouter.use('/', videoRouter);
baseRouter.get('/test', (req, res) => res.send('This is working!'));
module.exports = baseRouter;
Maybe i'm missing something on the heroku configuration? Thanks!

Ok, i fixed it. I had to change my procfile. It was running nuxt start not npm start so it wasn't running any of the server side code

Related

Failed to load module script: expected a javascript module script but server responded with a MIME type of text/jsx

Ive created an express server and created an api and also ive installed react through vite for my frontend. when I try to connect or load my main html file to the server the console gives that error. Im new to express
Here's My express app code
const express = require("express");
const dotenv = require("dotenv");
const errorMiddleware = require("./middleware/error");
const cookieParser = require("cookie-parser");
const fileupload = require("express-fileupload");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const path = require("path");
//config for env file
dotenv.config({ path: `${__dirname}/config/config.env` });
app.use(cors());
app.use(express.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb" }));
app.use(cookieParser());
app.use(fileupload());
// Route Imports
const productRoutes = require("./routes/productRoutes");
const userRoutes = require("./routes/userRoutes");
const orderRoutes = require("./routes/orderRoute");
const paymentRoute = require("./routes/paymentRoute");
//using all routes
app.use("/api/v1", productRoutes);
app.use("/api/v1/user", userRoutes);
app.use("/api/v1", orderRoutes);
app.use("/api/v1", paymentRoute);
app.use(express.static(path.join(__dirname, "../frontend")));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "../frontend/index.html"));
});
//error HAndler Middleware
app.use(errorMiddleware);
module.exports = app;
You can't serve your JSX files, you need to first build your front-end, so npm run build and then serve the content of your build folder ( in my case it's dist/ )
app.use(express.static(path.join(__dirname, "./front/dist/")));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "./front/dist/index.html"));
})

How to work on a hosted Website and make changes?

So I have a full stack website and the frond end is hosted on netlify via github and the backend is hosted on heroku. When I make changes on front end I have to push each change to github in order to see the result. I am a newbie and I do not know how should I work on a project locally when all my routes are netlify and heroku routes.
This is the code
const express = require("express");
const path = require("path");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const User = require("./models/userModel");
dotenv.config();
// set up server
const app = express();
app.listen(process.env.PORT || 5000, () =>
console.log(`Server started on port: ${process.env.PORT || 5000 }`)
);
app.get("/test", (req, res) => {
res.send("It works");
});
app.use(express.json());
app.use(cookieParser());
app.use(
cors({
origin: "https://awesome-murdock-.netlify.app/",
credentials: true,
})
);
// connect to mongoDB
mongoose.connect(
process.env.MONGODB_URI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
},
(err) => {
if (err) return console.error(err);
console.log("Connected to MongoDB");
}
);
// sign
// set up routes
app.use("/auth", require("./routers/userRouter"));
app.use("/customer", require("./routers/customerRouter"));
app.get('/', (req, res) => {
res.send('Hi')
})
as you can see cors is ponting to my netlify app and it has not connection with my back end and the same is with backend

Respond to client after receiving client to server POST request (Node.JS)

I have been attempting to respond to a client-side request with Node.JS. I have discovered Node JS - call function on server from client javascript, which seems to explain what I want, except that I can't seem to translate it to my program.
Here is the request via POST in index.html:
$.post("/", {data: 'hi'}, function(result){
$("body").html(result);
});
what I was hoping it would do would be write the result of the call, from my server.js (Node):
const express = require('express');
const path = require('path');
const http = require('http');
const fs = require('fs');
function handler(data, app){
if(req.method == "POST"){
app.setHeader('Content-Type', 'text/html');
app.writeHead(200);
app.end(data);
}
}
const BUILDPATH = path.join(__dirname);
const { PORT = 3000 } = process.env;
const app = express();
app.set('port', PORT);
app.use(express.static(BUILDPATH));
app.get('/*', (req, res) => res.sendFile('static/index.html', { root: BUILDPATH }));
const httpServer = http.createServer(app);
httpServer.listen(PORT);
console.info(`🚀 Client Running on: http://localhost:${PORT}`);
try this code:
const express = require('express');
const path = require('path');
const http = require('http');
const fs = require('fs');
function handler(data, app){
if(req.method == "POST"){
app.setHeader('Content-Type', 'text/html');
app.writeHead(200);
app.end(data);
}
}
const BUILDPATH = path.join(__dirname);
const { PORT = 3000 } = process.env;
const app = express();
app.set('port', PORT);
app.use(express.static(BUILDPATH));
app.get('/', (req, res) => {
res
// best practice is to always return an status code
.status(200)
// just return an json object
.json({"msg": "ok, it all works just fine"})
});
const httpServer = http.createServer(app);
httpServer.listen(PORT);
console.info(`🚀 Client Running on: http://localhost:${PORT}`);
The issue is, is that the only route your Node server listens to is the one you define with /*. As you can see, that route returns your index.html file to the client. You did not specify a route that listens for a request that comes from the client.
To solve the issue, you will have to define a route that listens on a specific route for the request you are trying to make from your client.
I see you are using ExpressJS. here is the documentation on writing routes.

NextJS throwing 404 when deployed to Vercel

I have a custom express server that I'm using with NextJS.
Everything works just fine when I'm developing locally, but when I deploy to Vercel, I catch 404s whenever I try to access my backend API.
What could be going wrong? Here's my server.ts:
import express from 'express';
import next from 'next';
import bodyParser from 'body-parser';
import { connectDbs } from './config/db';
import { listingsRouter } from './routes';
const PORT = process.env.PORT || 3003;
const dbs = ['mydb'];
const dev = process.env.NODE_DEV !== 'production';
const nextApp = next({ dev });
const handle = nextApp.getRequestHandler();
const applyMiddleware = (app) => {
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
};
const applyRoutes = (app) => {
app.use('/api/listings', listingsRouter);
};
const startServer = async () => {
await nextApp.prepare();
const app = express();
applyMiddleware(app);
applyRoutes(app);
app.get('*', (req, res) => handle(req, res));
await connectDbs(dbs);
app.listen(PORT, () => console.log(`App listening on port ${PORT}`));
};
startServer();
The Next.js documentation for custom servers:
A custom server cannot be deployed on Vercel, the platform Next.js was made for.
Source: Custom Server
Even though you can't deploy a custom server, you generally don't need to do so because Next.js supports Serverless Functions using the /pages/api directory.
Source: API Routes
Also take a look at this Guide explaining how to convert custom Next.js server to routes:
Source: Server to Routes Guide

404 Cannot POST Using Express

I´m trying to create an API Rest in NodeJs with Express.
I have my index.js with the following code:
const express = require('express');
const routesV1 = require('./routes/v1/index');
const app = express();
routesV1(app);
app.listen(4000, () => {
console.log('Running on port: 4000');
});
then i have a routes folder with another "index.js" and a "usersRoutes".
Here´s the code of the userRoutes:
const express = require('express');
const userController = require('../../controllers/v1/UserController');
const router = express.Router();
router.post('/create', userController.createUser);
router.post('/update', userController.updateUser);
router.post('/delete', userController.deleteUser);
router.get('/get-all', userController.getUsers);
module.exports = router;
and the code of the index.js into the routes folder:
const userRoutes = require('./UserRoutes');
const productRoutes = require('./ProductRoutes');
module.exports = app => {
app.use('api/v1/users', userRoutes);
};
but when i´m consuming via Postman, with the following url: http://localhost:4000/api/v1/users/create I´m receiving a 404 error code.
Can anybody help me? thanks
I resolved it adding '/' to the route in routes/index.js
const userRoutes = require('./UserRoutes');
const productRoutes = require('./ProductRoutes');
module.exports = app => {
app.use('/api/v1/users', userRoutes);
app.use('/api/v1/products', productRoutes);
};

Categories