KOA POST parsing error - node.js

I'm trying to get the POST data using koa-body-parser but I get the following error :
SyntaxError: Unexpected token e
at Object.parse (native)
This error refer to
/co-body/node_modules/raw-body/index.js
I think that the library co-body is trying to use "parse" but in my node version this function is restricted.
I'm using node 0.11.13
This is a part of the app.js
var path=require('path');
var koa = require('koa');
var app = koa();
app.use(require('koa-body-parser')());
//enrutamiento
app.use(require('./configs/routes')(app));
This is the function that recibe the call:
function *(){
/*
var str = 'email=lopezchr%40gmail.com&password=123123';
console.log(JSON.parse(str));
*/
var self = this;
var attributes= this.request.body
var userModel = this.models.user;
userModel.create(this.request.body).exec(function(){
self.body={success:true,description:"user Created"}
});
}
Aditionally, when I try to do this:
var str = 'email=lopezchr%40gmail.com&password=123123';
console.log(JSON.parse(str));
I optain the same error..
update
In other post, I realized that string is not a JSON.. sooo... that is the problem...
I'm trying to do this:
$.post('/auth',$(form).serialize(),function(data){
console.log(data);
});
And I want to recibe the form data with koa-body-parce...What should I do?

For some reazon, the jquery function $.post was sending the message with type json.. so that caused the error.. now the message type is plain/text and works.. thanks

Related

How to use module in my own node js module?

How I can use third party module in my own? For example if I have in app main file something like (using body-parser):
app.post("/dothis", (req,res)=>{
var name = req.body.name;
console.log(name);
};
This work fine. But when I want to have this in separate file (for example mod.js), and wrote like this:
exports.own = function(){
var name = req.body.name;
console.log(name);
}
Then in main file wrote:
const mod = require(__dirname + "/mod.js")
app.post("/dothis", (req,res)=>{
mod.own();
};
Then I get error like, req is undefined.
I am trying to add in mod.js file
const {req} = require ("http");
So then I got error that can't read value of name undefined.
There is the question, how i can transfer my code which is using body-parser, express and other modules to separate file or creating own module to get working module?
Thanks!
You are getting undefined because you are not passing the request.
Looking at your code, try this.
exports.own = function(req){ // use request
var name = req.body.name;
console.log(name);
}
const mod = require(__dirname + "/mod.js")
app.post("/dothis", (req,res)=>{
mod.own(req); // pass request
};

Variable inside a class is not defined NodeJS

I am develping an application to send emails with nodeJs 6.9 and express 4.
I am also using a library called powerdrill wich is the library that calls Mandrill APIs.
I am trying to use the message variable which is the varible that use the powerdrill library to create the object and send the email. I am using this variable inside a method but is throwing an error.
'use strict';
var config = require('config'),
queries = require('api/queries'),
Message = require('powerdrill').Message;
class MandrillService{
constructor(config, Message) {
this.config = config;
this.Message = Message;
}
welcome(){
//console.log(req.body);
message = new Message();
message.apiKey(config.mandrillKey)
.subject('Welcom')
.template('welcome-email')
.from(config.mandrilEmail)
.to('david#gmail.com')
.tag('complex')
.globalMergeVar('VERIFY_EMAIL','link')
.send(function(err, resp) {
});
}
}
module.exports = new MandrillService(config);
error:
Unhandled rejection ReferenceError: message is not defined
at MandrillService.welcome (/home/user/platform/services/mandrillService.js:28:17)
at /home/user/platform/services/notificationService.js:222:22
at Promise._execute (/home/user//platform/node_modules/bluebird/js/release/debuggability.js:303:9)
at Promise._resolveFromExecutor (/home/user/platform/node_modules/bluebird/js/release/promise.js:483:18)
I donĀ“t know what is the behavior inside a class but if I try to call the method using express inside a post method, and using it like follows the code works fine.
var express = require('express'),
router = express.Router(),
config = require('config'),
Message = require('powerdrill').Message;
router.post('/welcome',function(req,res,next){
message = new Message();
message.apiKey(config.mandrillKey)
.subject(req.body.subject)
.template(req.body.template)
.from(config.mandrilEmail)
.to(req.body.to)
.tag('complex')
.globalMergeVar('VERIFY_EMAIL',req.body.linkVefifyEmail)
.send(function(err, resp)
res.send(resp).end();
});
});

Testing Node Application with mocha

I have the following test application based on a template provided by openshift.
server.js:
var express = require('express');
exports.NodeTestApp = function () {
self.cache_get = function (key) {
return 'Would be a value here';
};
}
server_test.js:
var server = require('../server');
describe('Server', function(){
describe('Startup',function(){
it('sets up routes during startup',function(){
var app = server.NodeTestApp();
app.cache_get('/');
expect(app.routes.size).to.equals(5);
})
})
})
When I run this test I get an error message that cache_get is not defined.
TypeError: Cannot read property 'cache_get' of undefined
at Context.<anonymous> (test/server_test.js:7:16)
I would have thought that everything that is specified in the NodeTestApp function is available via variable app. IntelliJ even shows me the function as a valid call. Any idea why I get this error ?
Thanks in advance.
Oliver
I figured out the problem with above code. To instantiate the app variable the new keyword has to be used. I didn't think that this is required as I would have thought its purely a function call and not a constructor call, which requires the new keyword. Below is the working code for your reference.
var app = new server.NodeTestApp();

Error: GoogleMapsAPI is not defined for node-googlemaps

I am using node-googlemaps to query the Google Maps API from Node js. I have created my Server API key as a Developer. According to the this documentation, I have to make a publicConfig variable with my API key and certain other parameters. My publicConfig variable is as follows:
var gm = require('googlemaps');
var publicConfig = {
key: 'myKey',
stagger_time:1000, // for elevationPath
encode_polylines:false,
secure:true // use https
};
var gmAPI = new GoogleMapsAPI(publicConfig);
When I run the Code, I get the following error
ReferenceError: GoogleMapsAPI is not defined
Can somebody help me on this issue?
To Resolve this issue I had include the following line of Code
var GoogleMapsAPI = require('googlemaps');

java.lang.NoClassDefFoundError at runtime when using express framework and node.js

I am trying to write a sample code to create an instance of a java class and then invoke a method using that instance. I am using node-java module to do this. The code compiles without any error. However when I hit the URL which actually hits the same code then I get the class not found exception.
I have verified that the jar and it is there in the same directory as index.js and the jar also contains the class file (Application.class) for which the instance is being created.
My index.js file
var java = require("java");
java.classpath.push("demo.jar");
var express = require('express');
var router = express.Router();
var Application = java.import('Application');
/* GET home page. */
router.get('/', function(req, res) {
var application = new Application();
var resp = application.getResponse();
res.render('index', { title: resp });
});
module.exports = router;
Sorry for my english. I had the same problem. Look [https://github.com/joeferner/node-java/issues/147]
my code:
`var java = require("java");
var path=require("path");
var fs=require("fs");
console.log("ruta in directory",path.join(__dirname));
console.log("exist file:",fs.existsSync(path.resolve(__dirname,"./lib-java/lib-tgd.jar")));
java.classpath.push("commons-lang3-3.1.jar");
java.classpath.push("commons-io.jar");
java.classpath.push(path.resolve(__dirname,"./lib-java/lib-tgd.jar"));
java.classpath.push(path.resolve(__dirname,"./lib-java/jackson-annotations- 2.5.1.jar"));
java.classpath.push(path.resolve(__dirname,"./lib-java/jackson-core-2.5.1.jar"));
java.classpath.push(path.resolve(__dirname,"./lib-java/jackson-databind-2.5.1.jar"));`
with path.resolve solves the problem of the file path

Resources