Error in async, in Koa? - node.js

I want to implement an API with POST method, But when i am starting my server then Error occured:
3450:~/Desktop/koa/ctx$ node koa2.js
/home/358/Desktop/koa/ctx/koa2.js:9
router.post('/locations', async (ctx, next) =>{
^
SyntaxError: Unexpected token (
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
358#daffolap358-Latitude-3450:~/Desktop/koa/ctx$
Can anyone tell me where I am doing wrong ?
My code is :
server.js:
var Koa =require('koa');
var middleware =require('koa-router');
var logger =require('koa-logger');
var parser =require('koa-bodyparser');
const router = middleware();
const app = new Koa();
router.post('/locations', async (ctx, next) =>{
console.log("ctx");
});
app
.use(logger()) // Logs information.
.use(parser()) // Parses json body requests.
.use(router.routes()) // Assigns routes.
.use(router.allowedMethods())
app.listen(5050, () => console.log('Listening on port 5050.'));
export default app;

You are getting this error because your node version is less than 7.6.0.
It should be greater than 7.6 also Async/await support in Node 7.6 comes from updating V8, Chromium’s JavaScript engine, to version 5.5.

Check your Node version. It should be >= 7.6.0. Otherwise koa-2 and async-await pattern will not work.

Related

A regex works fine with Express Route Tester but it failed when it used with NodeJS

I used express in a NodeJs project, and i want to be able to request my server with theses routes :
/dogs
/pinguin
/bear
/wolf
/cat
/rat
I use a regex for this (http://forbeslindesay.github.io/express-route-tester/) :
Express Route Tester
It works correctly with express route tester but it failed when i tried with NodeJS
My code :
var express = require('express');
var app = express()
app.get("\/(dogs|pinguin|bear|wolf|cat|rat)", function (req, res) {
res.send('dogs or pinguin');
});
error :
return new RegExp(path, flags);
^
SyntaxError: Invalid regular expression: /^\/(?(?:([^\/]+?))|pinguin|bear|wolf|cat|rat)\/?$/: Invalid group
at new RegExp (<anonymous>)
at pathtoRegexp (C:\Users\Corentin\node_modules\path-to-regexp\index.js:128:10)
at new Layer (C:\Users\Corentin\node_modules\express\lib\router\layer.js:45:17)
at Function.route (C:\Users\Corentin\node_modules\express\lib\router\index.js:500:15)
at Function.app.<computed> [as get] (C:\Users\Corentin\node_modules\express\lib\application.js:481:30)
at Object.<anonymous> (C:\Users\Corentin\Documents\mesProjets\mdm\mdm-api\routes.js:36:5)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
try with the below code
app.get(/^\/(dogs|pinguin|bear|wolf|cat|rat)/, function (req, res) {
res.send('dogs or pinguin');
});

How to fix SyntaxError: Unexpected token ... while using socket.io in my local machine

I am trying to use socket.io on one of a simple project but when I run the same on my local machine I am getting this bug. I am not able to figure out what is going wrong my index.js is as follows
const app = require("express")();
const http = require("http").Server(app);
const io = require("socket.io")(http);
const port = process.env.PORT || 8080;
app.get("/", function(req, res) {
res.render("index.ejs");
});
http.listen(port, function() {
console.log("Listening on *:" + port);
});
The full log is here
Desktop/chat/node_modules/ws/lib/websocket.js:347
...options
^^^
SyntaxError: Unexpected token ...
at createScript (vm.js:74:10)
at Object.runInThisContext (vm.js:116:10)
at Module._compile (module.js:533:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Module.require (module.js:513:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (Desktop/chat/node_modules/ws/index.js:3:19)
My node version is 8.0
This looks like it's probably the object spread operator. If you showed the actual line of code that causes the error, we could see for sure.
You will need at least node v8.6 to get support for the object spread operator by default. Starting with node v8.21, it could be enabled via command line flags.

NodeJS - To perform request, define both url and callback

So I have been starting to get Nodejs to work and it seems like it is not going my way. I have been trying to learn using cloudscraper This code to be exact and whenever I run it with command node test.js it always return a error of
#!/usr/bin/env node
/* eslint-disable promise/always-return */
var cloudscraper = require('cloudscraper');
var fs = require('fs');
cloudscraper.get({ uri: 'https://subscene.com/content/images/logo.gif', encoding: null })
.then(function (bufferAsBody) {
fs.writeFileSync('./test.gif', bufferAsBody);
})
.catch(console.error);
Error: To perform request, define both url and callback
at performRequest (C:\Users\node_modules\cloudscraper\index.js:84:11)
at Object.cloudscraper.get (C:\Users\node_modules\cloudscraper\index.js:17:3)
at Object.<anonymous> (C:\Users\test.js:7:14)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
At this point I dont know what I am doing wrong and here I am asking what I am doing wrong?
EDIT:
Im leaving this thread but I fixed it by removing the node_modules and reinstalled from the beginning!
Did you try a minimalist version?
var cloudscraper = require('cloudscraper');
cloudscraper.get('https://subscene.com/content/images/logo.gif')
.then(function (bufferAsBody) {
console.log('success');
})
.catch(console.error);

Async/Await not running in Azure App Service

Within my Azure App Service Node.js backend I cannot seem to get the Javascript async/await feature to run. I have changed the default version of Node.js within application settings and package.json to above 7.6. (Changed to 8.9.0)
I would like to use this feature within a custom Express router shown here:
var express = require('express'),
bodyParser = require('body-parser');
var router = express.Router();
router.get('/', function (req, res, next) {
res.status(200).send('GET: This is a test response!');
});
router.post('/:id', async function (req, res, next) {
var context = req.azureMobile;
var newLovedOne = req.body.lovedone;
var newTie = req.body.tie;
console.log('POST: newLovedOne ', newLovedOne);
console.log('POST: newTie ', newTie);
try {
await context.tables('Tie').insert(newTie);
await context.tables('LovedOne').insert(newLovedOne);
} catch (error) {
res.status(500).send('Insert failed!');
}
});
module.exports = router;
Attempting to start the app with the above router produces this:
Application has thrown an uncaught exception and is terminated:
SyntaxError: missing ) after argument list
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (D:\home\site\wwwroot\app.js:12:20)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
To verify whether the Node.js version is correctly set, you can go to your root and open the iisnode.yml file. Make sure it has the following line with the correct version:
nodeProcessCommandLine: "D:\Program Files (x86)\nodejs\8.9.0\node.exe"

mongoose.connect not invoking callback after connection to mongodb

I'm trying to make a connection to MongoDB using Mongoose. But it does neither throw a error nor connect to the database. Following is my code.
const express = require('express');
const app = express();
const port = process.env.PORT || 8080;
const mongoose = require('mongoose');
console.log('Hi, there!!');
mongoose.connect('mongodb://localhost:27017/db_name', (err) => {
console.log('Callback called');
if(err) throw err;
console.log('Connected to database');
})
In the above code none of the console.log inside the callback do happen. But any place outside the mongoose.connect do work like console.log('Hi, there!!')
Versions Used
express: 4.0.0
mongoose: 3.8.40
node: 7.7.3
mongodb: 3.4.0
Using mongoose: 3.8.40 I got this in the console :
{ Error: Cannot find module '../build/Release/bson'
at Function.Module._resolveFilename (module.js:470:15)
at Function.Module._load (module.js:418:25)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Users/kevin/nemeacreation/sites/test/stackoverflow/node_modules/bson/ext/index.js:15:10)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3) code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
Hi, there!!
upgrading to "mongoose": "~4.4" fixed it for me. I got the answer here : https://stackoverflow.com/a/35516644/2829540
For info the latest release of mongoose is 4.10.4

Resources