I am completely new to server side javascript so any help would really be appreciated.
I recently followed this tutorial https://www.youtube.com/watch?v=p-x6WdwaJco to build a simple RESTful API with node.js mongodb and express. The tutorial also uses a library called node-restful https://github.com/baugarten/node-restful.
First of all I built a server.js in the root directory:
// Dependencies
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
// Mongo DB
mongoose.connect('mongodb://localhost/rest_test');
// Express
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Routes
app.use('/api', require('./routes/api'));
var test = require('./routes/api');
// Start Server
app.listen(3000);
console.log('API is running on port 3000')
Then I created api.js in root/routes
// Dependencies
var express = require('express');
var router = express.Router();
// Models
var Product = require('../models/product');
// Routes
Product.methods(['get', 'put', 'post', 'delete']);
Product.register(router, '/products');
// Return router
module.exports = router;
Finally I created a file called product.js within root/models:
// Dependencies
var express = require('express');
var restful = require('node-restful');
var mongoose = restful.mongoose;
// Schema
var productSchema = new mongoose.Schema({
name: String,
sku: String,
price: Number,
});
// Return model
module.exports = restful.model('Products', productSchema);
This is where my issue is(i think) - the server runs fine until I attempt to use .methods() and .register() on mongoose.Schema() from api.js. It keeps telling me that .methods is undefined in Product.
I have been through the tutorial over and over and can see nothing wrong with my code. All libraries seemed to have installed correctly. Mongo is running...
I have a feeling that mongoose.Schema is not registering properly but have no idea why as everything seems to be as it is in the tutorial - there are no similar complaints on the tutorial - so I can only assume this is "my problem" but I just can't see where I've gone wrong....
Thanks in advance....
I copied your code exactly and then was able to run it without any issues. So this most likely means there's some issue in your local environment. Most likely an old/outdated package.
In your root directory, create a file called package.json with the following contents:
{
"name": "stackoverflow-30492214",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node server.js"
},
"dependencies": {
"body-parser": "^1.12.4",
"express": "^4.12.4",
"mongoose": "^3.9.7",
"node-restful": "^0.1.18"
},
"devDependencies": {}
}
And then, in the same directory, in your terminal run npm clean && npm install. This should download/install/build dependencies as defined by the package.json. Once done, try running the server again node server.js. You might get a warning about the mongoose package being an unstable version, but you shouldn't see any .method() or .register() undefined errors.
Related
I'm unable to run a node terminal on my backend server.js file in my class project. I am NOT running this in my browser, I'm trying to run my localhost through my node terminal. I've tried looking through a few articles, I made sure that requirejs was installed, babel is installed, I've tried substituting in "import" rather than require, and to my knowledge, all of the necessary files are installed in my package.json.
When I run nodemon server, or node server, I get the following error message
const express = require('express');
^
ReferenceError: require is not defined
This is the code so far.
const express = require('express');
const cors = require('cors');
// const mongoose = require('mongoose');
const mongoose = require('mongoose')
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true });const connection = mongoose.connection;connection.once('open', () => { console.log("MongoDB database connection established successfully");})
const addLocationsRouter = require('./routes/addLocations.models');
const contactsRouter = require('./routes/contacts.models');
const homeRouter = require('../src/components/Home')
const allLocationsRouter = require('../src/components/alllocations')
app.use('/allLocations', allLocationsRouter)
app.use('/Home', homeRouter);
app.use('/addLocations', addLocationsRouter);
app.use('/contacts', contactsRouter);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
I've used require in other parts files in my backend folder and it doesn't throw an error. However, in my server.js file, I seemingly can't use the word require
Ok, I think I have it
uninstall axios, babel, and requirejs. You don't actually use those packages in your back end.
Then remove "type": "module" from your package.json
According to this issue, you should remove "type": "module" from your package.json file.
Can you verify that this happens in any directory? By default a .js file shouldn’t be treated as a module. I suspect that you may be in a directory (or nested directory below) where a package.json has a “type” field set to “module”.
#jkrems You are right. The module "type" was causing the issue. Thank you for flagging that out.
In addition, you have to ensure that you are requiring dotenv in the backend (in your file that has express), rather than in your frontend javascript files.
I created an Angular 7 application using the Angular CLI. I added my express server as one knows it. Afterwards I used the command "node server/app.js to start my app, but then in the browser in the "Elements" section there appears <app-root></app-root> without any content. As if the browser knew nothing about the actual Angular application. And when I run the ng serve command it seems to know about the actual Angular application, but there appears a 404 not found error in terms of post and get requests to the data server.
I already had a working Angular4 application with -I guess- the same setup and now same things seem to not work any longer.
I researched all day long to find the solution but for nothing.
I think it is not advantageous to post all my files in here. Comment if I was wrong and I am going to edit them.
Thanks in advance.
My app.js:
"use strict";
var bodyParser = require('body-parser');
const cors = require('cors');
// import { Observable } from 'rxjs';
var express = require("express");
var path = require("path");
var app = express();
app.use(cors());
const router = express.Router();
var nodeModulesPath = path.join(__dirname, "..", "node_modules");
app.use("/node_modules", express.static(nodeModulesPath));
var srcPath = path.join(__dirname, "..", "src");
app.use("/src", express.static(srcPath));
var serverPath = path.join(__dirname);
app.use("/server", express.static(serverPath));
// app.use(bodyParser.json());
var models = require("./models");
models.sequelize.sync({force:true}).then(function() {
console.log("TABELLE ERSTELLT");
// app.use(cors());
app.use("/", router);
app.use(bodyParser
.urlencoded({extended:true})
);
app.use(bodyParser.json());
console.log("after bodyparser");
app.get("/", function(req,res){
res.sendFile(path.join(__dirname, "views", "index.html"));
});
// app.get('/*', function(req, res) {
// res.sendFile(path.join(__dirname, "views", "index.html"));
// });
app.post("/goals/create",function (req, res){
models.Goal.create({
id: req.body.id,
name: req.body.name,
content: req.body.content,
firstGivenValue: req.body.firstGivenValue,
fittingValue: req.body.fittingValue,
someone_would_like_to_implement: req.body.someone_would_like_to_implement,
i_know_how_to_implement_it: req.body.i_know_how_to_implement_it
}).then(function(obj){
console.log(obj.id);
// res.end("erfolgreich");
res.redirect("/");
})
console.log(req.body);
});
app.get("/test",(req, res) => {
res.end("test erfolgreich");
});
app.listen(3000);
});
You mention that you think it used to work for angular 4. Currently you're serving the index.html from the src folder. That's not going to work, your app is a typescript app and will need to be compiled one way or another; not to mention the Angular compiler. In the early days (I think pre 4, but not sure) angular serve also write the served files in a folder in your project, so you could just pick those JIT compiled files up and toss them on a web server, or express server. Those days are gone (with good reason for that matter, mostly performance).
You will now have to create an explicit build (ng build) and tell your express server (app.js) to target your dist folder.
TL;DR:
Run ng build
Replace
var srcPath = path.join(__dirname, "..", "src");
app.use("/src", express.static(srcPath));
With:
var distPath = path.join(__dirname, "..", "dist");
app.use("/dist", express.static(distPath));
Made a very simple Timestamp Microservice app with node that I want to be able to run on a webpage on my website. How would I go about doing this? It currently works fine on my local server.
I feel like this would be very simple but from searching can only find how to deploy to Heroku/AWS.
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
//Create an instance of Express for the app and instantiate bodyParser and cors
const app = module.exports = express();
app.use(bodyParser.json());
app.use(cors());
app.get(`/dateValues/:dateVal`, (req,res,next) => {
//gets date from request
var dateVal = req.params.dateVal;
//Options for formatting date in natural state
var options = { year: 'numeric', month: 'long', day: 'numeric' };
if(isNaN(dateVal)) {
var naturalDate = new Date(dateVal);
naturalDate= naturalDate.toLocaleDateString('en-US', options);
var unixDate = new Date(dateVal).getTime()/1000-21600;
} else {
var unixDate = dateVal;
var naturalDate = new Date((parseInt(dateVal)+21600)*1000);
naturalDate= naturalDate.toLocaleDateString('en-US', options);
}
res.json({unix: unixDate, natural: naturalDate});
});
app.listen(3000, () => {
console.log('App is running');
});
is you want to push this online on your own server, it will be the same as you did in local.
Install your server, install npm/node, push your project on it and run npm start. This will work.
If you want something a bit better for production, you can use a proxy webserver, like apache or nginx and run your nodejs project with pm2
https://www.phusionpassenger.com/library/walkthroughs/deploy/nodejs/ownserver/nginx/oss/trusty/deploy_app.html
Heroku is the easiest deployment platfrom when it comes to node.js application. You can host it for free too. Checkout the url below.
https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction
i am following a project by udemy and i am having a TypeError: Cannot read property 'db' of undefined
var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodeblog');
/* GET home page. */
router.get('/', function(req, res, next) {
var deb = req.db;
var posts = deb.get('posts');
posts.find({},{},function(err, posts){
res.render('index',{
"posts": posts
});
});
});
module.exports = router;
I think it could be the version of your express. Go to your json file, delete the express and npm install express --save . The currently version is "express": "^4.15.2", if you are using 3.something could be it.
This error is because of the old version of express. Open package.json replace your old express version with "express": "^4.15.3" and then run npm install this will install the required package. Then run npm start to start the application.
I'm trying to send some data to a database using mongoose. Here is my code so far.
server.js
var express = require('express');
var wine = require('./routes/wines');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.get('/wines', wine.findAll);
app.get('/wines/:id', wine.findById);
app.listen(3000);
console.log('Listening on port 3000...');
wine.js (inside models folder)
var mongoose = require('mongoose');
var db = mongoose.connection;
var wineSchema = new mongoose.Schema({
name: String,
description: String
});
var Wine = mongoose.model('Wine', wineSchema);
module.exports = Wine;
wines.js (inside routes folder)
exports.addWine = function(req, res) {
// Problem not defined here
var silence = new Wine({ name: 'Silence', description:"cena" })
console.log(silence.name) // 'Silence'
// add it to the database
};
I keep getting this error and i have no idea why.
ReferenceError: Wine is not defined
I've exported Wine in wine.js (models), shouldn't I be able to use it everywhere ?
Thank you in advance !
Add var Wine = require('./../models/wine.js'); at the beginning of wines.js (assuming your routes and models folders are contained within the same directory).
Exporting objects/values/functions from node modules does not make them globally available in other modules. The exported objects/values/functions are returned from require (reference here for more info). That said, Mongoose uses an internal global cache for models and schemas which make it available via mongoose (or a connection) throughout an app.
So in your routes file you could do something like:
var Wine = mongoose.model('Wine'); // Notice we don't specify a schema
exports.addWine = function(req, res) {
var silence = new Wine({ name: 'Silence', description:"cena" })
console.log(silence.name) // 'Silence'
// add it to the database
};