stuck at building process while hosting on Vercel - javascript

I'm using node.js as a server-side to store the API respond, the app is working without any issue but recently I have been trying to host it on Vercel so I ran into many issue, the project get stuck at the building process...
the building output :
Building output
My server.js code :
// Setup empty JS object to act as endpoint for all routes
projectData = {};
// Require Express to run server and routes
const express = require('express');
// Start up an instance of app
const app = express();
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const Cors = require('cors');
app.use(Cors());
// Initialize the main project folder
app.use(express.static('website'));
// Setup Server
const port = 8000;
const Server = app.listen(port , run);
function run() {
console.log(`hello there :D`);
console.log(`here is ${port} ready to go`);
}
//GET method
app.get('/all', function(req,res){
res.send(projectData)
console.log(projectData);
})
//POST method
app.post("/addUserComment", function(req,res){
projectData = {
temp : req.body.temp,
date : req.body.date,
feeling : req.body.feeling,
}
console.log(projectData);
res.send(projectData);
})
My working directory and build settings :
Working directory
Build settings
note: server.js is my server-side file, and my website folder includes my app.js file and my HTML, CSS files, also i did try to add Vercel.json file but i couldn't understand how to use it, so if you gonna add this file in your answer please explain how and why

I think you need to remove the build command, because it's now trying to run the server.js file instead of making a build.

Related

POST http://127.0.0.1:5500/add 405 (Method Not Allowed)

Could you help me solve this error? It seems that I can not connect between server.js and app.js.
What I want to do is: display the result of the postData('/add', {answer:42}); and postData('/addMovie', {movie:'the matrix', score:5}); in the console.
Thank you for your help in advance.
error image
server.js
// Setup empty JS object to act as endpoint for all routes
projectData = {};
// Require Express to run server and routes
const express = require('express');//add
// Start up an instance of app
const app = express();//add
/* Dependencies */
const bodyParser = require('body-parser') //add
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
//we can connect the other packages we have installed on the command line to our app in our code with the .use() method
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const cors = require('cors');//add
app.use(cors());//add
// Initialize the main project folder
app.use(express.static('website'));
////////////////////creating a local server
const port = 5500;//add
// Setup Server
//////////////////////add
const server = app.listen(port, listening);
function listening(){
// console.log(server);
console.log(`running on localhost: ${port}`);
};
app.get('/all', function (req, res) {
res.send(projectData)
})
// POST route
const data = []
app.post('/add', callBack);
function callBack(req,res){
res.send('POST received');
console.log(data)
}
const movieData = []
app.post('/addMovie', addMovie )
function addMovie (req, res){
movieData.push(req.body)
console.log(movieData);
}
app.js
app.js
[Addition]
Thank you for your feedback!!
I changed the port in server.js, but nothing changed.
port5500
The issue was resolved.
// when using local server ( ≒ server.js in this case)
postData('/add', {answer:42});
postData('/addMovie', {movie:'the matrix', score:5});
// when using live server
postData('http://localhost:5500/add', {answer:42});
postData('http://localhost:5500/addMovie', {movie:'the matrix', score:5});
You need to add an "allow" in the header field to support this or explicitly allow it in your webserver configuration
A lot of the time, this is set up in the configuration of your .htaccess or nginx.conf file (depending on the webserver). It will commonly be found in your RewriteRule section. You can look for a "R=405" flag there.

How to deploy Node JS app cPanel from localhost to a server

I have created a simple Express JS app. and it is working fine in localhost. when I visit localhost:8000 I see static files (index.html, style.css and frontend.js).
I have tried to deploy that app in a server using cPanel. and I have installed Node app and dependencies using package.json successfully. But when I visit the domain I just see a message (Node JS app is working, Node version is 10.24.1).
How to make my app to point and display the static folder (index.html) and run the app?
My app architecture:
server.js
package.json
public/index.html
public/style.css
public/frontend.js
And here is my server.js startup file:
// Setup empty JS object to act as endpoint for all routes
projectData = {};
// Require Express to run server and routes
const express = require('express');
// Start up an instance of app
const app = express();
/* Dependencies */
const bodyParser = require('body-parser');
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const cors = require('cors');
app.use(cors());
// Initialize the main project folder
app.use(express.static('public'));
// Setup Server
const port = 8000;
const server = app.listen(port, function(){
console.log(`server running on localhost: ${port}`);
});
//POST Route to store data in the app endpoint, projectData object
app.post('/addData', addData);
function addData (req, res){
let data = req.body;
projectData = data;
console.log(projectData);
}
app.get('/getData', getData);
function getData(req, res) {
res.send(projectData);
}
The problem here is that you are not pointing a route to send the HTML file. Otherwise the client would have to point it to the correct path of the file, Like localhost:3000/index.html.
you need to send it from the server using app.get
app.get("/", (req, res) => {
res.sendFile(__dirname + "path to the file");
});
The problem was that I have created the app in a subfolder of my domain.
But when I have created subdomain and reinstalled the app inside it, the app is pointing to static folder successfully.

How to use socket.io across diffrent routes in node.js

I have different routes in my node js application and i have to use socket.io in every route to make my node and react js application realtime. But, i have the below structure of my node js application.
router.js
const express = require('express');
const router = express.Router();
const worksheetController = require('../controllers/worksheet')
const attendenceController = require('../controllers/attendence')
router.route('/worksheets')
.get(
worksheetController.getWorksheet
)
.post(
worksheetController.validateWorksheet,
worksheetController.addWorksheet,
attendenceController.markAttendence
)
router.route('/attendances')
.get(
attendenceController.getAttendance
)
module.exports = router;
server.js
const express = require('express');
const router = require('./router');
const app = express();
app.use('/api', router);
app.listen('5000', () => {
console.log('Listening on port');
});
module.exports = app;
So, I want to know
1) Should i need to use http module to create a server, if i need to use socket.io.
2) How can i use socket.io for diffrent routes.
I found posts that match's to my question on stackoverflow, which is this, this and this. But i don't think, that works for me. So please help me.
You can use http module or other module in document of socket.io for to use socket.io
I don't sure your idea. But when you want implement socket.io. I think you should run another node app. (Meaning you have 2 nodejs app. 1 for node http normally and 1 for socket.io app). After you can use path option when init socket.io app https://socket.io/docs/server-api/#new-Server-httpServer-options. Because when you deploy to production. You should run your socket.io app with beside of proxy serve (ex: nginx). Socket.io basically support multi transport and protocol. So if use with http restful. How about config your connection mapping from nginx to socket.io app, how you setup error handler ?.
In your case:
+ Create new file socket.js:
// socket.js
var http = require('http')
var socket_io = require('socket.io')
function init_socket(app) {
const server = http.Server(app)
const io = socket_io(server, { path: 'your-path-want-for-socket-io' }) // default: /socket.io/
}
import {init_socket} from 'socket.js'
init_socket(app)

Prerender Angular app on an already existing Node.js server

My goal is to have dynamic og: tags, that can be seen by the facebook crawler. By doing some research I figured the best (and probably the only) approach is to prerender my app on the server. However I'm having problems with doing that.
I already have an existing Node.js server which looks a little different from the servers in most online guides.
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
// Api for retrieving data from DB
const api = require('./server/api');
// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Angular DIST folder
app.use(express.static(path.join(__dirname, 'dist')));
// Api location
app.use('/api', api);
// Send all other requests to the Angular app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'))
})
// Set Port
const port = process.env.PORT || '3040';
app.set('port', port);
const server = http.createServer(app)
server.listen(port, () => console.log('Magic happens on localhost:' + port));
I've tried using prerender.io. I got an API key, installed prerender-node and put this right before redirecting the request to index.html:
app.use(require('prerender-node').set('prerenderToken', 'my-token'));
// Send all other requests to the Angular app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'))
})
I also added this to my index.html:
<meta name="fragment" content="!">
Nothing changed. Perhaps there's something else I need to do to get it working? Again, my goal is to have dynamic og: tags, that can be seen by the facebook crawler.
Additional info: For now, I'm setting the meta tags using the Meta serivce that comes with Angular 4, if it matters.
EDIT:
Demo link if someone wants to test: http://aramet.demo.cdots.bg/news-preview/1
Can you try moving the:
app.use(require('prerender-node').set('prerenderToken', 'my-token'));
above the static file line like:
app.use(require('prerender-node').set('prerenderToken', 'my-token'));
// Angular DIST folder
app.use(express.static(path.join(__dirname, 'dist')));
Since your index.html file is in your dist folder and you're serving static files from the dist folder, I'm wondering if the static call is serving your index.html file somehow.

How to pass value from app.js file to my client side file in node js?

Here I have one doubt, how can i pass value from node js app.js file to my client side js file.
Here My app.js file
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
var facebookAppId = '123456789023'
app.configure(function() {
app.use(express.static(__dirname + '/dist'));
app.use(express.logger('dev'));
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded() );
app.use(express.methodOverride());
});
app.listen(port);
Inside my dist folder i have index.html . that used to start run initially when i start app.js . So i would like to use the facebookAppId in my client side.How can i do that ?
Put it in it's own json file under a shared folder, then you can just require it like so in node:
shared/facebookInfo.json
{
"facebookAppId" : 123456789023
}
app.js
var facebookAppId = require('./shared/facebookInfo').facebookAppId;
...
// make sure to mount the directory as well so you can access it from the front end:
// it's being mapped to /shared here
app.use('/shared', express.static(__dirname + '/shared'));
...
And on the client side include it with ajax trough jquery or $http, whatever you are using.
A different approach could be to not put the file under a shared mounted folder, but include it during your front end build process.
This way you don't have to do an additional request to get in to your frontend and it's included more implicitly.
This is probably the most popular plugin to do that:
https://github.com/gruntjs/grunt-contrib-concat
This is off course somewhat assuming your frontend and backend are in the same repo. If they are in a different repo, you will have to put your shared data in a seperate repo as well, but that's a whole different question.

Categories