I am trying to run nodemon index.js in my terminal but I am getting the following error which I have absolutely no idea what it means as for me is very unclear.
Can please anyone explain to me how to solve this?
index.js
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var app = express();
var router = require('./services/router');
mongoose.connect('mongodb://localhost:apiAuth');
app.use(morgan('combined'));
app.use(bodyParser.json());
app.use('/v1', router);
var PORT = process.env.PORT || 3000;
var HOST = process.env.HOST || '127.0.0.1';
console.log('Listening on', HOST, PORT);
app.listen(PORT, HOST);
services/router.js
var router = require('express').Router();
function protected(req, res, next) {
res.send('Here is the secret!');
}
router.route('/protected')
.get(protected);
module.exports = router;
Terminal
[nodemon] restarting due to changes...
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Listening on 127.0.0.1 3000
(node:29104) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Slash in host identifier
(node:29104) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
The problem comes from your connection to MongoDB via Mongoose.
Short version :
You have entered a bad login URL:
mongoose.connect('mongodb://localhost:apiAuth');
^^^^^^^
I think you want to write (or something close to it):
mongoose.connect('mongodb://localhost:'+apiAuth);
Here's an example of a MongoDB login URL : mongodb://127.0.0.1:27017/my_db.
Or the doc: Standard Connection String Format
Long version :
The resolution of the problem is the same as above, but you would have located it yourself.
For my part, I proceeded like that (because I had exactly the same problem, with as much information).
Isolate the code that generates the error: You can simply comment on parts of your code to determine which zone is crashing.
Add a catch() after the connection with Mongoose: mongoose.connect(...).catch((e) => { console.log(e); throw e; }. This will have indicated directly the line concerned and some additional information.
This kind of technique works in a lot of cases.
I also have same error as like above (Error: Slash in host identifier). I resolved the issue. I am accessing mongooses as like below. My database password contains # so here is the problem when our password having # special character we need to pass with the help of encodeURIComponent. I passed the user name and password as like below its working fine for me.
Error:
mongoose.connect('mongodb://xxx-xx:7a?VNXd##sabfpV8=gRLwnNvC_8#196.89.12.168:27017/xxxxx',function(err,db){
if(err){
console.log(err);
}else {
console.log('connected to the Test db');
}
});
Resolved code:
mongoose.connect('mongodb://xxx-xx:'+encodeURIComponent("7a?VNXd###safpV8=gRLwnNvC_8")+'#196.89.12.168:27017/xxxxx',function(err,db){
if(err){
console.log(err);
}else {
console.log('connected to the Test db');
}
});
I was facing similar error, what i did is
Previous Error Causing Version:
mongoose.connect("mongodb://localhost:cat_app");
Working Version
mongoose.connect("mongodb://localhost/cat_app");
Both are same except : is replaced with /
Related
I'm getting an "app crashed" error in Visual Studio Code's terminal when I try to update a MySQL record in NodeJS.
app2.js:
const express = require('express');
const mysql = require('mysql');
// create connection
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'journey_test'
})
// connect to mysql
db.connect(err => {
if(err) {
throw err
}
console.log('MySQL Connected');
})
const app = express()
app.use(express.static('public'));
app.set('view engine', 'ejs');
// this pulls index.ejs to the root folder location of the site
app.get('/', function (req, res) {
res.render('index2');
});
app.post('/change/:artist/:id', (req, res) => {
let newArtist = req.params.artist;
let newID = req.params.id ;
// even hard-setting variables in my query causes failure
let sql = `UPDATE tblbillboardcomplete SET artist = 'The Cure' WHERE id = '104'`
let query = db.query(sql, err => {
if(err) {
throw err
}
res.send('Entry updated');
})
})
app.listen('3000', () => {
console.log('Server Started on port 3000')
})
index2.ejs:
<!DOCTYPE html>
<html>
<head>
<script>
function testing() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
const text = this.responseText;
const obj = JSON.parse(text);
document.getElementById("Hello2").innerHTML = "Yes!";
};
xhttp.open("POST", "change/The Cure/104", true);
xhttp.send();
}
</script>
</head>
<body>
<button style= "height:22px";" type="button" onclick="testing()">Update</button>
<div id="Hello2">Did I do it?</div>
</body>
</html>
The error in Powershell:
PS C:\Users\Mervius\Documents\NodeJS> nodemon app2.js
[nodemon] 2.0.12
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app2.js`
Server Started on port 3000
MySQL Connected
C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE tblbillboardcomplete SET artist = 'The Cure' WHERE id = '104'' at line 1
at Query.Sequence._packetToError (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Query.ErrorPacket (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\protocol\sequences\Query.js:79:18)
at Protocol._parsePacket (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\Connection.js:88:28)
at Socket.<anonymous> (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:375:28)
at addChunk (internal/streams/readable.js:290:12)
--------------------
at Protocol._enqueue (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Connection.query (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\Connection.js:198:25)
at C:\Users\Mervius\Documents\NodeJS\app2.js:36:24
at Layer.handle [as handle_request] (C:\Users\Mervius\Documents\NodeJS\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Mervius\Documents\NodeJS\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\Mervius\Documents\NodeJS\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Mervius\Documents\NodeJS\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Mervius\Documents\NodeJS\node_modules\express\lib\router\index.js:281:22
at param (C:\Users\Mervius\Documents\NodeJS\node_modules\express\lib\router\index.js:354:14)
at param (C:\Users\Mervius\Documents\NodeJS\node_modules\express\lib\router\index.js:365:14) {
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE tblbillboardcomplete SET artist = 'The Cure' WHERE id = '104'' at line 1",
sqlState: '42000',
index: 0,
sql: "UPDATE tblbillboardcomplete SET artist = 'The Cure' WHERE id = '104'"
}
[nodemon] app crashed - waiting for file changes before starting...
Query that works in MySQL Console:
You can see it works.
Using WAMP server (because I'm rebuilding a previous Visual Basic WinForms app as a web app):
MySQL: 5.7.9
Apache: 2.4.17
I swear the above worked just a few days ago, but the environment may have changed a little in that time (e.g. installing more node modules, that kind of thing, though I was definitely using the WAMP server at the time).
Any help appreciated.
Edit: I'm experiencing no problem selecting from or inserting into the MySQL database using NodeJS.
ADDED (after John Michael Manlupig's suggestion initially worked, at least in the original context):
The problem persists in another spot. I'm posting info (as "result") to app.js via a tinymce rich-text editor, but it fails out the same way when using the code below:
const express = require('express');
const mysql = require('mysql');
//const dayjs = require('dayjs');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/result', upload.none(), function (req, res, next) { // when we save RTE info in tinymce
var newEntry = req.body.content
var newDate = activedate
const sql = `UPDATE main SET entry = ? WHERE dateID = ?`;
const query = db.query(sql, [newEntry, newDate], err => {
if(err) {
throw err
}
res.send('Entry updated');
})
});
I can send the received value of "req.body.content" to the console, and it's good, but sending it through the rest of the code causes "app crashed" in the same way as described above, despite parametizing as suggested by #John Michael Manlupig, and despite the query text containing correct/expected info, and being useable as-is in MySQL Console.
Anything obvious I'm overlooking?
You should parametize the values instead of inserting it directly into the string.
const sql = `UPDATE tblbillboardcomplete SET artist = ? WHERE id = ?`;
const query = db.query(sql, ['The Cure', 104], err => {
if(err) {
throw err
}
res.send('Entry updated');
});
I think I've identified the ghost in the machine. I recently started saving useful blocks of code in OneNote, and was then recently copying-n-pasting from OneNote into Visual Studio Code. Visual Studio wasn't telling me anything was wrong, and lots of it worked, but it looks strongly like there was invisible junk in there (at least some of the time). Ugh!
Thanks for all the help, as it was a necessary part of the solution!
I am currently working on a react/express project and I get this error:
Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://reactjs.org/link/crossorigin-error for more information.
I have enabled CORS in my server.js like this:
const express = require("express"),
app = express(),
port = process.env.PORT || 5000,
cors = require("cors");
{Sequelize, Model, QueryTypes } = require('sequelize');
app.use(cors());
app.use(express.json());
I also have no issues with displaying the original data in console.
This is basically what causes it to break.
allDetails=JSON.parse(details);
Getting and sending the data:
async function connect() {
var detailsArray=[]
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (err) {
console.error('Unable to connect to the database:', error);
}
info = await sequelize.query('select * from Information', { type: QueryTypes.SELECT });
let details = JSON.stringify(info);
detailsArray=JSON.parse(details);
return details;
}
app.get("/list", async (req, res) => {
const result = await connect();
res.json(result);
});
I also made sure to npm install for both my client and server side a few times to double check and triple check that it was installed.
Am I missing something?Or do I need anything in my client side to solve this issue. This is very confusing and whatever solution I tried for my CORS issue did not work either. Powershell is also not giving any errors regarding me trying to parse my data. I am not very familiar with cross origin related errors so an explanation would be very much appreciated.
When this error happens:
The error happens when I try to JSON.parse() the data received but when using console.log to display the raw data it is fine. So before that nothing breaks.
If I understand correctly, you are running both front-end and server on your local machine during development and getting CORS error, if so, since you are using express and have already required the CORS module, you still need to use it as a middleware to your express app - Express - Using middleware:
const express = require("express");
const app = express(),
const port = process.env.PORT || 5000,
const cors = require("cors");
app.use(cors());
app.listen(5000);
I have a collection on MongoDB from which I'm trying to query all the elements using find():
const mongoose = require('mongoose');
const Featured = mongoose.model('featured');
module.exports = app => {
app.get('/api/featured', async (req, res) => {
console.log("featured route");
const featured = await Featured.find();
console.log(featured);
res.send(featured);
})
}
Here's Featured.js:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const featuredSchema = new Schema({});
mongoose.model('featured', featuredSchema);
However, I'm getting the error upon making the request:
(node:75568) UnhandledPromiseRejectionWarning: MongooseError: Operation `featureds.find()` buffering timed out after 10000ms
at Timeout.<anonymous> (/Users/prikshetsharma/Desktop/humboiserver/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:184:20)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
(node:75568) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
How to fix this error and get all the collection items to return with find()? Strangely, the error shows featureds.find() whereas I've never used featureds word in my code anywhere.
For anyone else who might stumble upon this: My issue had to do with a faulty connection, and I managed to fix it by using mongoose.connect instead of mongoose.createConnection.
Please note the Mongoose documentation saying:
Mongoose will not throw any errors by default if you use a model without connecting.
...which just results in a buffering timeout instead.
if you are on localhost, using
mongoose.connect('mongodb://localhost:27017/myapp');
try using 127.0.0.1 instead of localhost
mongoose.connect('mongodb://127.0.0.1:27017/myapp');
Quick Fixes:
Export model in Featured.js:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const featuredSchema = new Schema({}, { collection: "featured" });
module.exports = mongoose.model('featured', featuredSchema);
UnhandledPromiseRejectionWarning: Unhandled promise rejection,
You need to wrap your service code in try catch block,
const mongoose = require('mongoose');
// correct this path to your original path of Featured.js
const Featured = require('./Featured.js');
app.get('/api/featured', async (req, res) => {
try {
console.log("featured route");
const featured = await Featured.find();
console.log(featured);
res.send(featured);
}
catch(e) {
console.log('Catch an error: ', e)
}
});
featureds.find() buffering timed out after 10000ms,
there would be many possibilities,
Remove the mongoose module from node_module and also from *.json files, reinstall mongoose module and try again.
Check if you have connected with database or not, after that check if you have the correct network access to your database cluster.
If anyone is using Mongo db Atlas then they need to whitelist their IP address to authorize the access.
Steps to authorize the access.
Get your systems IP address
For Mac User : Hit this command on terminal . curl ifconfig.me
For Windows user : Hit this command on command Prompts . ipconfig /all
You can find your IP Address by web also. eg. https://whatismyipaddress.com/
Once you have your networks IP address:
Go to Mongo DB Atlas -> Network Access -> IP Access List - Add your IP address. You can share access to specific IP address or you can keep open access for all as well.
Why am I getting a segmentation fault error whenever I type in any node commands?
A bit of background information: I'm trying to deploy any basic demo node app (in GoDaddy's shared hosting) following these instructions (from the comment from user called 'x.g.'). I do everything and get to the very last instruction (number 5) where it states to type node app.js & and I get the following response in the terminal:
[1] 326516
If I type node app.js without the ampersand & I get this error:
Segmentation fault
Does anyone know why this happens and how to fix it? I basically have (as per the instructions) an app.js with this simple code:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('NodeJS server running on Shared Hosting\n');
});
server.listen(port, hostname, () => {
console.log('Server running at http://${hostname}:${port}/');
});
Also, whenever I type anything like node, npm or node-v it also states the Segmentation fault error. Any help would be much appreciated!
Update: any ideas anyone?
I have a JavaScript proxy server that often hangs up after having used it a while. This is the proxy code:
var express = require(["express"], function(){}),
http = require(["http"], function(){}),
port = (process.env.PORT || 8001),
server = module.exports = express(),
httpProxy = require(['http-proxy'], function(){});
var proxy = httpProxy.createProxyServer();
// SERVER CONFIGURATION
// ====================
server.configure(function() {
server.use(function(req, res, next) {
if (req.url.indexOf('/any/thing') === 0) {
//console.log(res);
proxy.web(req, res, {target: 'http://any.thing.com'});
} else {
next();
}
});
server.use('/anything', express["static"](__dirname + "/../public"));
server.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
server.use(express.bodyParser());
server.use(server.router);
});
// Start Node.js Server
http.createServer(server).listen(port);
I am trying to do some tests with Nightwatch.js. The tests work up to a point, then the server crashes. In some tests this point is always reached at the same time, in others it depends when the server crashes and if it crashes at all.
This is the Error message:
C:...\node_modules\http-proxy\lib\http-proxy\index.js:119
throw err;
^
Error: socket hang up
at createHangUpError (_http_client.js:215:15)
at Socket.socketCloseListener (_http_client.js:247:23)
at Socket.emit (events.js:129:20)
at TCP.close (net.js:485:12)
Stopping Express server
What could be the reason for this? I was not able to figure it out in google.
The error is thrown when parallelly sending requests to the http-proxy.
The error can be prevented by installing a different version of http-proxy.
For me the error occured in http-proxy version 1.6.2.
I fixed the problem by installing version 1.0.0:
npm uninstall http-proxy
then
npm install http-proxy#1.0.0