how to deploy angular app using nodejs - javascript

I'm using a nodejs backend (following this tutorial to pull in tweets into the front end of my application.
Now that I'm ready to deploy to a development server, I've packaged the frontend with ng build --prod, and that looks and works fine, except for the module with loading tweets. How do I host the node server part of the application to display the tweets properly?
Here are the files of my node app. It's held in the root of my project folder, outside of src.
server.js
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var functions = require('./functions');
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
app.post('/authorize', functions.authorize);
app.post('/search', functions.search);
app.listen(3000);
console.log('listening now');
functions.js
var request = require('request');
var config = require('./config');
functions = {
authorize: function(req, res) {
var header = config.consumerkey + ':' +config.consumersecret;
var encheader = new Buffer(header).toString('base64');
var finalheader = 'Basic ' + encheader;
request.post('https://api.twitter.com/oauth2/token', {form: {'grant_type': 'client_credentials'},
headers: {Authorization: finalheader}}, function(error, response, body) {
if(error)
console.log(error);
else {
config.bearertoken = JSON.parse(body).access_token;
res.json({success: true, data:config.bearertoken});
}
})
},
search: function(req, res) {
var searchquery = req.body.query;
var encsearchquery = encodeURIComponent(searchquery);
var bearerheader = 'Bearer ' + config.bearertoken;
request.get('https://api.twitter.com/1.1/search/tweets.json?q=' + encsearchquery +
'&result_type=recent', {headers: {Authorization: bearerheader}}, function(error, body, response) {
if(error)
console.log(error);
else {
res.json({success: true, data:JSON.parse(body.body)});
}
})
}
}
module.exports = functions;
config.js
var appsettings = {
consumerkey: 'key',
consumersecret: 'key',
bearertoken: ''
};
module.exports = appsettings;
package.json
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "brooklynbrim",
"license": "MIT",
"devDependencies": {
"body-parser": "^1.17.2",
"cors": "^2.8.4",
"express": "^4.15.4",
"request": "^2.81.0"
}
}

I would recommend you to host your nodeJS app on Heroku.
You can get started Here.
And for the Angular App, I would recommend you Firebase. Easiest way to host your angular app. How to deploy Angular apps on Firebase

Related

Deploying app to Heroku throws error { path=β€œ/” path=β€œ/favicon.ico” }. But runs on localhost

I am trying to deploy my app to Heroku. I am getting 503 (Service Unavailable) error even though it runs on localhost. I have tried many solutions, but none of them are working. My app.js file
if (process.env.NODE_ENV !== "production") {
require("dotenv").config();
}
const express = require("express");
const mongoose = require("mongoose");
const { ApolloServer } = require("apollo-server-express");
const auth = require("./middleware/auth");
const userController = require("./controllers/userController");
const typeDefs = require("./schema");
const resolvers = require("./resolvers");
const port = process.env.PORT || 4000;
const app = express();
app.set("port", port);
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"OPTIONS, GET, POST, PUT, PATCH, DELETE"
);
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
app.use(auth);
app.get("/email-confirmation/:token", userController.confirmationPost);
const server = new ApolloServer({
typeDefs,
resolvers,
formatError: (err) => {
if (!err.originalError) {
return err;
}
if (err.message.startsWith("Database Error: ")) {
err.message = "Internal server error";
}
const data = err.originalError.data;
const message = err.message || "Internal server error.";
const code = err.originalError.code || 500;
return { message: message, status: code, data: data };
},
context: ({ req, res }) => ({
req,
res,
}),
});
server.applyMiddleware({ app });
mongoose
.connect(process.env.DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() => {
console.log("conneted to database");
app.listen(port, () => {
console.log("listening for requests on port " + port);
});
});
And my package.json is:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js",
"dev": "nodemon app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"apollo-server-express": "^2.17.0",
"bcryptjs": "^2.4.3",
"crypto": "^1.0.1",
"express": "^4.17.1",
"graphql": "^15.3.0",
"jsonwebtoken": "^8.3.0",
"mongoose": "^5.10.2",
"nodemailer": "^6.4.16",
"nodemailer-sendgrid-transport": "^0.2.0",
"validator": "^10.8.0"
},
"devDependencies": {
"dotenv": "^8.2.0",
"eslint": "^7.7.0",
"nodemon": "^2.0.6"
}
}
heroku logs --tail command gives following output:
I have tried every solution. But none of them seems to resolve the issue. Please, help.
UPDATE:
After I setup DB_URL in Heroku, it started working but I am getting another error.
Console:
1. GET https://capstone-ecommerce-backend.herokuapp.com/ 404 (Not Found)
2. Refused to load the image 'https://capstone-ecommerce-backend.herokuapp.com/favicon.ico' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.
Try setting up the DB_URL in your Heroku application. Use the following command:
$ heroku config:set DB_URL=database_uri_here

Deployed React + Node.js application to Heroku and receiving Cannot GET / Error?

I have been working with another developer and we have been able to deploy the React + Node.js application using Express to Heroku, however we are still receiving an error as shown below in the screenshot.
I am apparently getting a 404 from the server and I feel that we are close to resolving the problem; we just do not know if it is a simple syntax fix or structure in general.
Here is my root package.json file:
{
"name": "dev-personal-portfolio-2",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js",
"server": "nodemon index.js",
"test": "echo \"Error: no test specified \" && exit 1",
"post-build": "cd client && npm i && npm run build"
},
"author": "",
"license": "ISC",
"dependencies": {
"#sendgrid/mail": "^7.2.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"nodemon": "^2.0.4"
}
}
Here is the server.js file:
require ('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const buildPath = ('build/index.html');
const port = process.env.PORT || 5000;
const sendGrid = require('#sendgrid/mail');
const server = express();
server.use(bodyParser.json());
server.use(cors());
// server.use((req, res, next) => {
// res.setHeader('Access-Control-Allow-Origin', '*');
// res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
// res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// next();
// });
// server.get('/api', (req, res, next) => {
// res.send('API Status: Running')
// });
server.use(express.static('client/build'));
// server.use('/static', express.static('public'))
// server.use(express.static(path.resolve(__dirname, './public')));
// server.get('*', (req, res) => {
// res.sendFile(path.resolve(__dirname, 'index.html'));
// });
console.log(express.static('client/build'));
console.log(`${__dirname}/public/index.html`);
server.use(express.json());
const REACT_APP_SENDGRID_API_KEY =`${process.env.REACT_APP_SENDGRID_API_KEY}`
server.post('/api/email', (req, res, next) => {
sendGrid.setApiKey(REACT_APP_SENDGRID_API_KEY);
console.log(req.body);
const msg = {
to: 'kevgill95#gmail.com',
from: req.body.email,
subject: req.body.subject,
text: req.body.message
}
sendGrid.send(msg)
.then(result => {
res.status(200).json({
success: true
});
})
.catch(err => {
console.log('error: ', err);
res.status(401).json({
success: false
})
})
});
server.listen(port, () => {
console.log(`Server is up on port ${port}!`);
});
NOTE: for the console.logs, here is what is returning from them:
console.log(express.static('client/build'));
[Function: serveStatic]
console.log(${__dirname}/public/index.html);
/Users/kevingillooly/dev-personal-portfolio-2/public/index.html
We have tried commenting out lines of code as well to try to resolve the problem, but we have not encountered anything that works.
If anyone would know what the problem would be, that would be awesome. The build succeeds just fine however the problem is very vague and we have tried a lot of different methods.

How can I send file from postman to node js?

I want to upload file from postman to node js but I have problem.
POSTMAN
Write url,check post method,check form-data,check file,write file name and choose file
This is my code
app.js
const express = require('express');
const bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
app.use(fileUpload());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
router.js
router.post('/schedule/entry', function(req,res){
console.log(req.file.name);
});
Console return me undefined name, if I write this code
router.post('/schedule/entry', function(req,res){
console.log(req.file);
});
Return 'undefined'
Why?
package.json
{
"name": "nodejs-rest-api-authentication",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.16.1",
"csv-array": "0.0.22",
"csv-write-stream": "^2.0.0",
"express": "^4.14.1",
"express-fileupload": "^0.3.0",
"fast-csv": "^2.4.1",
"formidable": "^1.1.1",
"json2csv": "^3.11.5",
"jsonwebtoken": "^8.1.0",
"mysql": "^2.15.0"
}
}
server.js
const app = require('./app');
const port = process.env.PORT || 3000;
const server = app.listen(port, function() {
console.log('Server listening on port ' + port);
});
screenshots
screenshots
codeGit
Based on the discussion in the comment section:
const express = require('express')
const app = express()
const formidable = require('formidable')
const path = require('path')
const uploadDir = '' // uploading the file to the same path as app.js
app.post('/', (req, res) =>{
var form = new formidable.IncomingForm()
form.multiples = true
form.keepExtensions = true
form.uploadDir = uploadDir
form.parse(req, (err, fields, files) => {
if (err) return res.status(500).json({ error: err })
res.status(200).json({ uploaded: true })
})
form.on('fileBegin', function (name, file) {
const [fileName, fileExt] = file.name.split('.')
file.path = path.join(uploadDir, `${fileName}_${new Date().getTime()}.${fileExt}`)
})
});
app.listen(3000, () => console.log('Example app listening on port 3000!'))
Attached Screenshots:
Because of body-parser middleware file will be not available in req so you must use another middleware libraries like connect-busboy or multer or connect-multiparty

Why is my app hanging on localhost?

I have recently built an MVC (well, more like a VC app) app in NodeJS and Express. Everything was working fine until I installed express-validator and pasted the middleware in the app file. Afterwards, localhost began hanging, with a GET / - - ms - - message in the console. I started a new app, reinstalled the modules, and copied and pasted the code. I still had the same issue, so I removed the express-validator middleware. Nothing changed.
App.js (entry point):
var config = require('./server/configure');
var express = require('express');
var app = express();
var app = config(app);
app.set('port', process.env.port || 3300);
app.set('views', __dirname + '/views');
app.listen(app.get('port'), function(req, res){
console.log('Server up: http://localhost:' + app.get('port'));
});
The routes file (/server/routes.js)
var express = require('express');
home = require('../controllers/home');
module.exports = function(app) {
router = express.Router();
router.get('/', home.home);
app.use(router);
};
The configure module (/server/configure.js)
var path = require('path'),
routes = require('./routes'),
ejs = require('ejs'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
module.exports = function(app) {
app.use(morgan('dev'));
app.use(bodyParser.json);
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser({
uploadDir: path.join(__dirname, 'public/upload/temp')
}));
app.use(methodOverride());
app.use(cookieParser('secret value'));
routes(app);
app.use('/public/', express.static(path.join(__dirname, '../public')));
if ('development' === app.get('env')) {
app.use(errorHandler());
}
app.set('view engine', 'ejs');
return(app);
};
The home controller (/controllers/home.js):
module.exports = {
home: function(req, res) {
res.render('home');
}
};
The Package file (package.json):
{
"name": "krementcookdev",
"version": "1.0.0",
"description": "the krementcook web application",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Isaac Krementsov",
"license": "ISC",
"dependencies": {
"body-parser": "*",
"cookie-parser": "*",
"ejs": "*",
"errorhandler": "*",
"express": "*",
"express-handlebars": "*",
"express-validator": "*",
"method-override": "*",
"morgan": "*",
"path": "*"
},
"devDependencies": {}
}
Of course, I have a view file (home.ejs) in the /views directory. If you need to see it, let me know and I will add it to the post. Please do not close this a being a duplicate; I have checked similar problems and they mostly regard simple apps without routers or anything like that. I tried the solutions offered that applied to me, but none were relevant or productive.
Update: I did have specific versions in the package file, but I still had the same issue.
Try to use specific version (latest) of individual package in dependencies. for more detail Refer - https://docs.npmjs.com/files/package.json

Express .post routing method undefined

I'm new to nodejs and express and I can't seem to phantom as per why this method isn't resolved in Webstorm. The .get method returns fine, testing it with the .all method works fine aswell. I have no clue why the .post method is unresolved, node starts up fine but if I try to send a post request to it through Postman it just gives an error:
the Postman error
app.js
'use strict';
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var routes = require("./routes");
app.use(function (req, res, next) {
console.log(`${req.method} ${req.originalUrl}`);
next();
});
app.use(bodyParser.json());
app.use("/questions", routes);
// routes(app);
var port = process.env.PORT || 3000;
app.listen(port, function () {
console.log("Express is running at", port);
});
routes.js
'use strict';
var express = require("express");
var router = express.Router();
// GET /questions
// Route for getting all questions
router.get("/", function (req, res) {
res.json({
response: "You sent me an awesome GET request, thank you!"
});
});
// POST /questions
// Route for creating a question
router.post("/questions", function (req, res) {
res.json({
response: "You sent me an awesome POST request, thank you!"
});
body: req.body;
});
module.exports = router;
package.json
{
"name": "02-express-api",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.15.2",
"express": "^4.13.4"
}
}
router.post("/questions", should be router.post("/", for this to work; right now, that handler is responding to the URI /questions/questions since the router itself gets attached to handle URIs under /questions.

Categories