i have a vue js project created with
vue create vue-js-client-crud
and built it with command
npm run build
file : router.js
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
export default new Router({
mode: "history",
routes: [
{
path: "/",
alias: "/products",
name: "tutorials",
component: () => import("./components/List")
},
{
path: "/products/:id",
name: "products-details",
component: () => import("./components/product")
},
{
path: "/add",
name: "add",
component: () => import("./components/Add")
}
]
});
ran into an example where , this vue js project is served by using express js via another project. so the set up is , create another nodewithExpress project, see sample package.json file and server.js. once this project is created, we create a views folder and then copy dist folder content from vue js project to this project. does this work and i didn't fully understand the set up. so in the express project , do we set up the routes exactly the same as we have in vue js project ? but this set up shouldn't work with spa pages , right?
{
"name": "nodeWithexpress",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.1"
}
}
file : server.js
const express = require("express");
const cors = require("cors");
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get("/", (req, res) => {
res.json({ message: "hello express." });
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`start server on port ${PORT}.`);
});
Related
EDIT: To be clear, this only happening when i'm trying to host the app. Works PERFECT during local environment testing..
When trying to fetch data from my backend getting an error in Chrome saying that JS is not enabled. (IT IS) so that is not the issue..
Thinking there may be an issue with my package.json maybe if the commands are incorrect for use on the host machine? Have tried Render & Heroku same issues.
I had tried to run the commands within my local environment and the app works flawlessly fetching data as intended. Only when hosting the app do I not get any data back from the server when making API call from the front end, instead get JS not enabled error in the Network tab and no errors on Front End that I can see..
Hosted app to see network error: https://elf-invasion.herokuapp.com/
File Structure:
/root
|- config.js
|- server.js
|- package.json + package-lock.json
|- client/
|- vue.config.json
|- ... (rest of dist, src, node_modules, public etc.)
|- models/
|- Elf.js + HighScore.js
|- routes/
|- api/
|- elf.js + highScore.js
config.js
module.exports = {
hostUrl: process.env.HOST_URL,
mongoURI: process.env.MONGO_URI,
PORT: process.env.PORT || 3000,
};
server.js
const express = require("express");
const app = express();
const port = 3000;
const mongoose = require("mongoose");
const { PORT, mongoURI } = require("./config.js");
// routes
const Player = require("./routes/api/player");
const Elf = require("./routes/api/elf");
const HighScore = require("./routes/api/highScore");
// cors is a middleware that allows us to make requests from our frontend to our backend
const cors = require("cors");
// morgan is a middleware that logs all requests to the console
const morgan = require("morgan");
// body-parser is a middleware that allows us to access the body of a request
const bodyParser = require("body-parser");
const path = require("path");
app.use(cors());
// use tiny to log only the request method and the status code
app.use(morgan("tiny"));
app.use(bodyParser.json());
// chek if we are in production
if (process.env.NODE_ENV === "production") {
// check if we are in production mode
app.use(express.static("client/dist"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "dist", "index.html"));
});
}
// test if server is running and connected to mongoDB
app.get("/", (req, res) => {
res.send("Hello World!");
});
// app.get("/", (req, res) => {
// res.send("Hello World!");
// });
// use routes
app.use("/api/", Player);
app.use("/api/", Elf);
app.use("/api/", HighScore);
mongoose
.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useUnifiedTopology: true,
})
.then(() => console.log("MongoDB connected..."))
.then(() => {
// log uri to console
console.log(`MongoDB connected to ${mongoURI}`);
})
.catch((err) => console.log(err));
app.listen(PORT, () => {
console.log(`Example app listening at ${PORT}`);
});
package.json
{
"name": "week1",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"server": "nodemon server.js --ignore 'client/'",
"client": "npm run serve --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"start": "node server.js",
"build": "npm install --prefix client && npm run build --prefix client"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.1",
"bootstrap": "^5.2.3",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"mongoose": "^6.7.5",
"morgan": "^1.10.0",
"portal-vue": "^2.1.7"
},
"devDependencies": {
"concurrently": "^7.6.0",
"nodemon": "^2.0.20"
}
}
My folder Structure look like this :
The code inside of server.js :
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));
// create a GET route
app.get('/express_backend', (req, res) => {
res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
});
The code inside of App.js (reside in client folder) :
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
state = {
data: null
};
componentDidMount() {
// Call our fetch function below once the component mounts
this.callBackendAPI().then(res => this.setState({ data: res.express })).catch(err => console.log(err));
}
// Fetches our GET route from the Express server. (Note the route we are fetching matches the GET route from server.js
callBackendAPI = async () => {
const response = await fetch('/express_backend');
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">{this.state.data}</p>
</div>
);
}
}
export default App;
package.json :
{
"name": "dtdc-inside",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
},
"proxy": "http://localhost:5000/"
}
I have run "node server.js" without error.
cd over to client directory and run "npm start" also without error.
But, data from server.js doesn't displayed in the browser.
I need help to understand why that happened. Thank you for your attention and forgive my poor english.
Server.js file requires some changes to server properly
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
//Optional: add this line to parse incoming data. In case you want to accept data
app.use(express.json());
// create a GET route
app.get('/express_backend', (req, res) => {
//generate output in `json` format rather than `send`.
res.json({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
});
//execute your server after writing all logic.
// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));
Thank you for your attention. With folder structure change (make a new folder called "backend" in the root directory, then move the file "server.js" into inside this folder), the code is now working. Thank you –
I am trying to create a simple node.js app on heroku. Here is my app.js:
console.log("Starting App")
const express = require('express')
const app = express()
const port = 3000
app.listen(process.env.PORT || port, () => console.log(`App listening on port ${port}!`))
app.get('/', (req,res) => {
res.sendFile(__dirname+'/public/index.html')
})
app.get('/style', (req,res) => {
res.sendFile(__dirname+'/public/main.css')
})
app.get('/script', (req,res) => {
res.sendFile(__dirname+'/public/script.js')
})
app.get('/changelog', (req,res) => {
res.sendFile(__dirname+'/public/changelog.txt')
})
here is my package.json file:
{
"name": "",
"version": "0.0.0",
"description": "",
"main": "/App.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.4"
}
}
and here is my Procfile:
web: node app.js
I am deploying this to heroku via github, and whenever I run the program it gives me an error, saying Cannot find module '/app/app.js.' I have made everything lowercase and removed forward slashes. I still get this error: Error: Cannot find module '/app/app.js' Can anyone help?
In package.json, change "main": "/App.js" to "main": "app.js"
make sure package.json is at the same level as app.js
If app.js is in another folder, make sure to provide the full path from directory holding the package.json file.
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
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