Having trouble setting up mern in Visual Studio code

  • Thread starter billllib
  • Start date
  • #1
69
2

Main Question or Discussion Point

I am having an error setting up mern

https://www.digitalocean.com/community/tutorials/getting-started-with-the-mern-stack#testing-api

I have to assume I didn't follow the instruction properly.The error is under Database section from the link above. When I type

Code:
require('dotenv').config()
into the terminal. The error I get is

Code:
Method invocation failed because [System.String] does not contain a method named 'config'.
At line:1 char:1
+ require('dotenv').config()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
My directories look like this


Inside models is todo.js and inside routes is api.js.

Do you think inside .env I have the wrong password? Also in visual studio advance when I save .env it comes back as .env.txt
Here is what my files look like

todo.js
JavaScript:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

//create schema for todo
const TodoSchema = new Schema({
action: {
type: String,
required: [true, 'The todo text field is required']
}
})

//create model for todo
const Todo = mongoose.model('todo', TodoSchema);

module.exports = Todo;
api.js
JavaScript:
const express = require ('express');
const router = express.Router();
const Todo = require('../models/todo');

router.get('/todos', (req, res, next) => {

//this will return all the data, exposing only the id and action field to the client
Todo.find({}, 'action')
.then(data => res.json(data))
.catch(next)
});

router.post('/todos', (req, res, next) => {
if(req.body.action){
Todo.create(req.body)
.then(data => res.json(data))
.catch(next)
}else {
res.json({
error: "The input field is empty"
})
}
});

router.delete('/todos/:id', (req, res, next) => {
Todo.findOneAndDelete({"_id": req.params.id})
.then(data => res.json(data))
.catch(next)
})

module.exports = router;

index.js
JavaScript:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const routes = require('./routes/api');
const path = require('path');
require('dotenv').config();

const app = express();

const port = process.env.PORT || 5000;

//connect to the database
mongoose.connect(process.env.DB, { useNewUrlParser: true })
.then(() => console.log(`Database connected successfully`))
.catch(err => console.log(err));

//since mongoose promise is depreciated, we overide it with node's promise
mongoose.Promise = global.Promise;

app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});

app.use(bodyParser.json());

app.use('/api', routes);

app.use((err, req, res, next) => {
console.log(err);
next();
});

app.listen(port, () => {
console.log(`Server running on port ${port}`)
});
 

Answers and Replies

  • #2
pbuk
Science Advisor
Gold Member
1,427
405
It does look as though your .env file is actually called .env.txt - you can see this from the file description in File Explorer - you should have 'hide extensions for known file types' turned off by default in File Explorer and then it would be clearer.

Are you in Visual Studio or Visual Studio Code? For node I can't see much advantage in using VS, I just use VS Code. It could be that there is some VS "magic" going on that is adding the .txt extension, I have never had this problem in VS Code.
 
  • Like
Likes DaveC426913 and sysprog
  • #3
69
2
I am in Visual Studio Code. The .txt extension was automatic upon saving the file.
 
  • #4
1,442
760
If the first field in a file name begins with a period mark, as .env does, it won't be treated as an extension, and a default extension will be appended to it; you should rename the file.
 
  • #5
69
2
I tried naming the file .env .I am sorry if I am not following.
 
  • #6
1,442
760
Try renaming it to something.env, where 'something' is the right name for whatever the file is defining environment conditions for.
 
  • #7
69
2
I found a problem when I save the file it is saving it as plaintext, where the save as type column is. I fixed the problem by saving it to all files. Was that what you were trying to say? Also when I add something.env the terminal still gets the same error. I also tried just .env and get the same error. Also index.js etc is saved as a javascript file is that correct file type. The exact name of index.js is index inside the directory stored in the computer
 
Last edited:
  • #8
1,442
760
Please understand what @pbuk said about turning off 'Hide extensions for known file types'.

In Windows Explorer, from any folder: Tools > Folder options > View > unclick 'Hide extensions for known file types'. Then click the 'Apply to Folders' button at the upper left. Then click 'OK' at the bottom left center.

You should then be able to see full filenames. That should make things clearer. I'm glad that you were able to find a workaround.
 
  • #9
pbuk
Science Advisor
Gold Member
1,427
405
Try renaming it to something.env, where 'something' is the right name for whatever the file is defining environment conditions for.
No, the file needs to be called .env - it uses the POSIX convention where files and folders that start with a period (often referred to as dotfiles) are used for configuration and are normally hidden from the user.
I found a problem when I save the file it is saving it as plaintext, where the save as type column is. I fixed the problem by saving it to all files. Was that what you were trying to say? Also when I add something.env the terminal still gets the same error. I also tried just .env and get the same error. Also index.js etc is saved as a javascript file is that correct file type. The exact name of index.js is index inside the directory stored in the computer
This whole notion of tight coupling between extensions and file 'types' is a Windows thing. Node is a cross-platform environment, and VS Code is a cross-platform tool so it uses the OS's 'save file' dialog. This is not helpful, as you have found.

You have found a solution already, but I'll show you the way I do it. This has the advantage of bypassing the system dialog altogether so works consistently across Windows and Linux and any other platform VS Code runs in.

Instead of creating a file in VS Code using the menu, right-click in the file panel in VS Code (where the blue circle is below) and this will bring up a dialog with a 'New File' option which doesn't have the Microsoft extension nonsense.

Capture.PNG


Alternatively, rename the file after creating it by right-clicking on the file in the directory pane to bring up the dialog below.

1592036861587.png


On a different tack, Windows is fine as a Node devlopment environment but I've never run a MongoDB server on Windows, and I wouldn't try. If I wanted to develop using the mern stack I'd use a Linux virtual machine - I use VirtualBox (which is free) and Mint MATE, but any flavour of Ubuntu would be OK for a Linux beginner. As long as your machine is reasonably powerful this works well.

I'd also recommend using a Git service: BitBucket and GitLab both have free plans for private repos. This means that you can easily develop and deploy code interchangably on your host Windows instance, a Linux guest or on a Cloud instance.
 
  • #10
1,442
760
pbuk said:
No, the file needs to be called .env - it uses the POSIX convention where files and folders that start with a period (often referred to as dotfiles) are used for configuration and are normally hidden from the user.
Thanks, @pbuk ##-## Visual Studio is not my long suit ##\dots##
 
  • #11
69
2
I need to ask another question to the forum. I want to create a mobile friendly forum that can be viewed from mobile and a social media site. My pc isn't that powerful. Do you think mern is the correct tools? I am an amateur. Also I want it viewable from pc and mac.

Also everything looks fine and I am still getting the same error
 
Last edited:
  • #12
1,442
760
I need to ask another question to the forum. I want to create a mobile friendly forum that can be viewed from mobile and a social media site. My pc isn't that powerful. Do you think mern is the correct tools? I am an amateur.
[You might get more specifically-interested views and topic-specific replies if you post a new thread -- members tend to look at topics before deciding whether to read or post.]

The short answer to you question is no, You'd be better of downloading phpBB, (available free at https://www.phpbb.com/), or some other free open-source forum product, than trying to write thousands of lines of code all by yourself.

Where do you envision putting your forum? Have you considered a free or low-cost hosting service? You can run phpBB on a free site hosted by uhostfull (https://www.uhostfull.com/). They'll occasionally send you emails inviting you to upgrade to a paid arrangement, but nothing obnoxious. If you do that, you can start it as a 'sandbox' site, and code your .htaccess file to request that search engines don't index you ##-## most well-behaved ones heed that ##-## and you'll want a good FTP client such as Filezilla (available for free download at https://filezilla-project.org/).

Try to decide as best you can what functionality you want, and then look for something realistic that can help you to implement that ##-## more design thinking and cultivation of awareness of what's available will serve you better in your endeavor than will efforts to figure out how to code everything yourself.

I don't want to try to dissuade you from learning to code ##-## I think it's great, and you appear to me to be making a good beginning -- please keep it up ##-## I think that it will impart to you valuable knowledge and skill that will serve you well in all your computational endeavors.
 
  • #13
69
2
When I say amateur I know the basics of coding and have used flask a little and know sql databases. With the forum I want to be able to easily create new categories easily like reddit but more like a forum interface. I also want to merge it with the social media idea. Do you still think using a forum creation tool better? I also realize chances of success of the idea is slim but still want to continue at worst I get better at coding.

Also everything looks fine and I am still getting the same error with visual studio advance. Any advice? Can the online forum you linked be modified by writing new code?
 
  • #14
1,442
760
I stand by my recommendation for phpBB. It's open source, and doesn't require compilation, so you can modify the code as you see fit (the license allows that for your copy, but doesn't allow you to distribute a modified version without permission). As it sits, it can easily accommodate your stated requirements. But you can check it out on their site, perhaps look at their showcase of phpBB sites at https://www.phpbb.com/showcase/, and decide for yourself.
 
  • Like
Likes billllib and pbuk
  • #15
pbuk
Science Advisor
Gold Member
1,427
405
I need to ask another question to the forum. I want to create a mobile friendly forum that can be viewed from mobile and a social media site. My pc isn't that powerful.
You don't need anything particularly powerful to do development. I do most of my open source development on a second hand PC I bought for less than GBP150 (saving my much more powerful laptop for client work).

But you must not contemplate even for a second running a public web site on your own PC using your domestic broadband. I won't go into why, just don't.

Do you think mern is the correct tools?
Maybe, but I don't think it is a good idea to start from scratch. The easiest software to deploy is based on PHP and MySQL because there are thousands of web hosts that support it. Like sysprog I recommend PHPBB and also Simple Machines Forum. If you are willing to learn a lot about running a server as well as writing code for the web you could look at NodeBB which will get you into the world of Node.

Why don't you install one of these three and then look at writing a plugin to add some functionality?

Also I want it viewable from pc and mac.
Any web-based software is viewable from a pc, mac, phone, TV or even some refrigerators.

Also everything looks fine and I am still getting the same error with visual studio advance.
What is Visual Studio Advance?
 
  • Like
Likes sysprog and billllib
  • #16
69
2
Sorry I mistyped, I meant Visual Studio code. I was thinking the same thing that I can use an already created forum creation tool like phpBB and create extensions. What languages are the extensions created in phpBB? I think php and node.js.

I found a link that walks you through extensions found here https://area51.phpbb.com/docs/dev/3.3.x/extensions/ .
Are there any other resources? I prefer videos but the link above could work. Does anyone here have any experience creating phpBB extensions? I ask because I might want to ask some questions.

I found a neat video that walks you through the process of installing phpBB forum but you need domain name and hosting company. I just want to create a prototype and upload it the internet at a later time any advice? . I am not sure prototype is the correct term but hopefully you get what I am trying to say.

Thanks everyone for the advice.
 
  • #17
pbuk
Science Advisor
Gold Member
1,427
405
What languages are the extensions created in phpBB? I think php and node.js.
Just PHP, although there may be some JavaScript involved for the front end.
Are there any other resources? I prefer videos but the link above could work. Does anyone here have any experience creating phpBB extensions? I ask because I might want to ask some questions.
I haven't done anything with phpBB since version 2 and I see that means it must have been about 15 years ago - so not very relevant now. You would probably be better off asking for help on the PHPBB support forums (Area 51 if I remember rightly).

This looks like a useful up to date resource and Quick Install will take you through a local machine install for development.
 
  • Like
Likes sysprog

Related Threads on Having trouble setting up mern in Visual Studio code

  • Last Post
Replies
7
Views
25K
Replies
25
Views
13K
Replies
7
Views
2K
Replies
17
Views
734
Replies
17
Views
867
Replies
5
Views
6K
Replies
6
Views
9K
Replies
10
Views
5K
Replies
10
Views
2K
  • Last Post
Replies
6
Views
3K
Top