Having trouble setting up mern in Visual Studio code

In summary: 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.In Summary,I am having an error setting up mern.When I typerequire('dotenv').config()into the terminal, the error I get isMethod invocation failed because [System.String] does not contain a method named 'config'.
  • #1
billllib
77
2
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}`)
});
 
Technology news on Phys.org
  • #2
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
I am in Visual Studio Code. The .txt extension was automatic upon saving the file.
 
  • #4
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
I tried naming the file .env .I am sorry if I am not following.
 
  • #6
Try renaming it to something.env, where 'something' is the right name for whatever the file is defining environment conditions for.
 
  • #7
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
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
sysprog said:
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.
billllib said:
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
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
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
billllib said:
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
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
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
billllib said:
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 website on your own PC using your domestic broadband. I won't go into why, just don't.

billllib said:
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?

billllib said:
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.

billllib said:
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
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
billllib said:
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.
billllib said:
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

1. What is MERN and why is it used?

MERN is a full-stack JavaScript framework that consists of four main components: MongoDB, Express, React, and Node.js. It is commonly used for building dynamic and interactive web applications due to its ability to handle both front-end and back-end development.

2. How do I install MERN in Visual Studio Code?

To install MERN in Visual Studio Code, you will need to first install Node.js and MongoDB on your computer. Then, you can use the npm command to install the necessary packages for Express, React, and Node.js. After that, you can create a new project in Visual Studio Code and start coding using the MERN stack.

3. What are some common issues when setting up MERN in Visual Studio Code?

Some common issues when setting up MERN in Visual Studio Code include compatibility issues with different versions of packages, incorrect installation of Node.js and MongoDB, and errors in code that prevent the application from running properly. It is important to carefully follow installation instructions and troubleshoot any errors that may arise.

4. How can I debug my MERN application in Visual Studio Code?

You can debug your MERN application in Visual Studio Code by using the built-in debugger tool. You can set breakpoints in your code and step through it to identify any errors or bugs. Additionally, you can use console.log() statements to log information and track the flow of your application.

5. Are there any resources available for learning how to use MERN in Visual Studio Code?

Yes, there are many resources available for learning how to use MERN in Visual Studio Code. You can find tutorials, documentation, and online courses that cover the basics of MERN development and how to set it up in Visual Studio Code. You can also join online communities and forums to ask for help and advice from experienced developers.

Similar threads

  • Programming and Computer Science
Replies
2
Views
318
  • Programming and Computer Science
Replies
16
Views
3K
  • Programming and Computer Science
Replies
5
Views
14K
Back
Top