Body is missing from request - node.js

I'm building a express app, and I'm using express-validator (https://github.com/ctavan/express-validator).
I'm using it as a middleware:
export default function verifyLogin(req, res, next) {
req.checkBody({
'email': {
notEmpty: true,
isEmail: {
errorMessage: 'Invalid Email'
},
errorMessage: "Empty"
},
'password': {
notEmpty: true,
errorMessage: 'Empty',
"isLength": {
options: [{min: 5, max: 20}],
errorMessage: "Password must be between 5 and 20 chars long"
}
}
});
req.getValidationResult().then(result => {
if(!result.isEmpty()) {
res.send(result.array());
console.log('In here, wrong params');
} else {
next();
}
});
}
But if I change res.send(result.array()); to res.status(422).send(result.array()); the body of the request is missing if I log it at the first line after the function (before I use req.CheckBody).
I'm total clueless of the behaviour. Any clues?
Added:
I get a empty body if I send a post request from angular and using res.status().send, but not from postman.
If I use res.send() - both postman and angular works.

The problem was that content-type was not specified in the angular2 app.
For some reason, when using res.status(), the content-type needed to be specified, but not when res.send() was used.

Related

How to login using Nuxt-auth module with a Node back and mongoDB

I'm currently creating an auth system using Mongo as database, Node with express as backend, and Nuxt as frontend.
I've found this authentication module https://auth.nuxtjs.org/ followed the doc, and the youtube video. I'm using Local scheme for Jwt system.
My issue is the login doesn't work successfully.
I think it doesn't work because of my user route on the backend, but not sure about that.
I also read that their is a user.autoFetch but dont know how to use it.
nuxt.config.js
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
'#nuxtjs/auth'
],
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {
baseURL: 'http://localhost:3000/'
},
auth: {
strategies: {
local: {
endpoints: {
login: { url: 'api/auth/login', method: 'post', propertyName: 'token' },
user: { url: 'api/auth/user', method: 'get', propertyName: 'data.attributes' },
logout: false
},
tokenType: ''
}
}
},
login.vue
async submit() {
try {
let response = await this.$auth.loginWith('local', { data: this.login })
console.log(response)
} catch (err) {
console.log(err)
}
// await this.$router.push('/dashboard');
},
The response send me back a 200 status, a token, and the userId (which is in my db) but the $auth still send me loggedIn at false and I can't get information like $auth.user.email.
I tried to change the auth endpoints in the nuxt.config.js
Changed tokenType: '' to tokentype: 'Bearer'
Changed the #nuxtjs/auth version to the same as the video tutorial. (4.8.4)
I added a controller for the route user :
route :
router.get('/user', userCtrl.getUser);
controller:
exports.getUser = (req, res, next) => {
User.findOne({ _id: req.params.id })
.then(thing => res.status(200).json(thing))
.catch(error => res.status(404).json({ error }));
}
Do not hesitate to ask me more details, on the configuration, other parts of the code, or anything like that.
Thank you in advance for any kind of help !

Hapi-Swagger failing with header value

I am using hapi-swagger in our application where one of API trying to use custom header but when I ivoke that API with custom header getting below error
{
"statusCode": 400,
"error": "Bad Request",
"message": "Invalid request headers input"
}
Below the API where I am using headers with validator.
{
method: 'POST',
path: '/v1/testapi',
config: {
description: 'Greet user',
notes: ['Use to greet a user'],
tags: ['api'],
handler: function ( request, h ) {
console.log('sending response...');
return h.response('OK');
},
validate: {
headers: {
name: Joi.string().required()
}
}
}
}
Below are the versions we are using.
"hapi": "17.2.2",
"hapi-swagger": "9.1.1",
"joi": "13.1.2",
I ran into this recently. You need to use the allowUnknown validation option to allow unknown headers (https://github.com/hapijs/hapi/issues/2407#issuecomment-74218465).
validate: {
headers: Joi.object({
name: Joi.string().required()
}).options({ allowUnknown: true })
}
Also note that hapi 17 changed the default behavior for reporting validation errors. If you want to log or return the actual error indicating which headers are failing validation rather than a generic "Bad Request" you can add a custom failAction hander (https://github.com/hapijs/hapi/issues/3706).

(Angular4 / MEAN) Sending Request to Local API Results in Empty Body

I'm trying to post data to an Items API, for instance:
"data": {
"title": "stack",
"notes": "asdsad",
"time": "19:02",
"meridian": "PM",
"type": "Education",
"_id": "5a2f02d3bba3640337bc92c9",
"days": {
"Monday": true,
"Tuesday": false,
"Wednesday": false,
"Thursday": false,
"Friday": false,
"Saturday": false,
"Sunday": false
}
}
However, when using HttpClient to post the data
this.http.post("http://localhost:3000/api/items",
JSON.stringify(item))
.subscribe(
(val) => {
console.log("POST call successful value returned in body",
val);
},
response => {
console.log("POST call in error", response);
},
() => {
console.log("The POST observable is now completed.");
});
I always get the Bad Request 400 response from the Items Controller in the API.
exports.createItem = async function(req, res, next){
// Req.Body contains the form submit values.
console.log(req);
console.log(req.body);
var item = {
id: req.body.id,
title: req.body.title,
days: req.body.days,
notes: req.body.notes,
time: req.body.time,
meridian: req.body.meridian,
type: req.body.type,
completed: req.body.completed,
}
try{
// Calling the Service function with the new object from the Request Body
var createdItem = await ItemService.createItem(item)
return res.status(201).json({status: 201, data: createdItem, message: "Succesfully Created Item"})
} catch(e){
console.log(e);
//Return an Error Response Message with Code and the Error Message.
return res.status(400).json({status: 400, message: "Item Creation was Unsuccesfull"})
}
}
I have already set up BodyParser in my app.js as so
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
In the express console, the output is as follows
_startTime: 2017-12-11T22:35:18.204Z,
_remoteAddress: '::1',
body: {},
secret: undefined,
cookies: {},
signedCookies: {},
route:
Route {
path: '/',
stack: [ [Object], [Object] ],
methods: { post: true } } }
{}
As you can see the body is empty and this is preventing an item from being created. I have gone ahead and tested this using Postman and when sending url encoded form data and raw JSON data the posts are successful and return 200. However, I can never get the application's request to work.
Any help is appreciated as I have been struggling with this for several hours now.
this.http.post("http://localhost:3000/api/items",
JSON.stringify(item) -----> convert JSON object to string
).subscribe(...);
Based on your server side code, I believe that it expects JSON object other than a JSON string, therefore remove JSON.stringify(item)) from your client side, the body of your POST should be JSON object.

bot configuration on kik is not working as expected

I am trying to create an echo bot on kik. I have followed dev.kik.com, created a bot but then when i am trying to configure the bot, it does nothing(no message on kik or my middleware).
set up:
1. I have echo bot implemented using nodejs and hosted on azure. I have tested with AdvanceREST and i know that if the message is received correctly, it does respond back.
2. I have tried sending my bot configuration as below via nodejs request module.
request.post({
url : 'https://api.kik.com/v1/config',
auth: {
'user' : 'botname',
'pass' : 'botkey'
},
headers:{
'Content-Type': 'application/json'
},
form :JSON.stringify({
"webhook": "https://myurl",
"features": {
"manuallySendReadReceipts": false,
"receiveReadReceipts": false,
"receiveDeliveryReceipts": false,
"receiveIsTyping": false
}
})
}, function(err,httpResponse,body){
if(err){
res.send(err);
}
if(httpResponse.statusCode === 200){
res.send(JSON.parse(body));
}
});
any help in this regard is greatly appreciated... thanks
request.post({
url : 'https://api.kik.com/v1/config',
auth: {
'user' : 'botname',
'pass' : 'botkey'
},
headers:{
'Content-Type': 'application/json'
},
json: true,
body :{
"webhook": "https://myurl.com/incoming",
"features": {
"manuallySendReadReceipts": false,
"receiveReadReceipts": false,
"receiveDeliveryReceipts": false,
"receiveIsTyping": false
}
}
}, function(err,httpResponse,body){
if(err){
res.send(err);
}
if(httpResponse.statusCode === 200){
res.send(JSON.parse(body));
}
});
This should work
a) ensure your url is valid, I know you just had a placeholder there but
b) Use json:true and the key body it will work
You could also checkout kik's node library https://www.npmjs.com/package/#kikinteractive/kik which can set a config easily
The config api is very picky. I managed to get it to work by using the following POST request, I used Postman. The key was to send an empty object as the features value:
POST /v1/config HTTP/1.1
Host: api.kik.com
Content-Type: application/json
Authorization: Basic --------- my auth token -----------------
Cache-Control: no-cache
Postman-Token: 217953a0-64da-556e-6817-5309bf4b92e8
{
"webhook": "https://kwcraftbeer.azurewebsites.net/incoming",
"features": {}
}

Custom Headers on Restler Get

I'm using Dan Wrong's Restler for Node Express to connect to an API. One of my endpoints requires a custom header is sent, but I'm having no luck in sending this:-
restler.get('api.co.uk/user',
{ username: 'xx', password: 'xx' },
{ headers: { 'token': cookie }})
.on('complete', function(user) {
res.render('dashboard.ejs', { user: user });
})
.on('error', function(error) {
res.render('500.ejs', { error: error });
})
I've tried variations of how to include the headers - but nothing seems to work, the header never seems to pass. Does anyone have any suggestions on how to achieve this please?
Help appreciated.
Try this:
restler.get('http://api.co.uk/user', {
query : { username: 'xx', password: 'xx' },
headers : { token: cookie }
}).on(...)

Resources