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.
Related
I'm trying to send multiple notifications using the messaging.sendAll() function of the Firebase Admin SDK.
The way in which I write the messages to send is this:
const messages = [];
const token2 = user2Data.notificationToken;
messages.push({
notification: {
title: `title`,
body: "this is the body!",
icon: "default",
sound: "customNotificationSound.wav",
content_available: "true",
},
data: {
notificationType: "notif2",
uid1: toUser,
uid2: fromUser,
},
token: token2,
});
const token1 = user1Data.notificationToken;
messages.push({
notification: {
title: `title`,
body: "this is the body!",
icon: "default",
sound: "customNotificationSound.wav",
content_available: "true",
},
data: {
notificationType: "notif1",
uid1: toUser,
uid2: fromUser,
},
token: token1,
});
return admin.messaging().sendAll(messages).then((promMes) => {
console.log("messages are sent");
console.log(promMes);
});
I don't know why but the messages to the different devices have not been sent.
I know that because of the promise I receive after I call the method sendAll(). In fact the error I get in the log is this:
textPayload: " { success: false, error: [FirebaseMessagingError] },"
I suppose that the problem hides behind how I construct the message payload but I wouldn't know how to fix it.
I'm having issues creating a subscription with stripe using a lambda function, this code runs fine locally but it is returning "internal server error" when posting to lambda, there are no logs in cloudwatch.
code for lambda function is below
exports.handler = async (event, context, callback) => {
// GET ITEMS
const { productId, customerId, currency = "gbp" } = JSON.parse(event.body);
let paymentMethods;
try {
paymentMethods = await stripe.paymentMethods.list({
customer: customerId,
type: 'card',
});
} catch (e) {
return {
statusCode: 200, // http status code
body: JSON.stringify({
"error" : true,
"msg" : "error retrieving payment method",
"data" : null
})
};
}
console.log(paymentMethods)
// Setup subscription
try {
const subscription = await stripe.subscriptions.create({
customer: customerId,
default_payment_method: paymentMethods.data[0].id,
items: [
{price: productId},
],
});
console.log(subscription)
// SUCCESS
return {
statusCode: 200, // http status code
body: JSON.stringify({
"data" : "success",
"error" : false,
"msg" : null
})
};
// ERROR
} catch (e) {
console.log(e);
return {
statusCode: 200, // http status code
body: JSON.stringify({
"error" : true,
"msg" : "error",
"data" : null
})
};
}
};
I can see the log for the payment methods but the log for the subscription is never shown, this does, however, create the subscription correctly in the stripe portal against that customer but no response is found from aws just a 500 internal server error.
any help would be greatly appreciated.
turns out I had my lambda function set to a 3-second timeout! as soon as I increased it the function worked fine, hopefully, this might help someone out with the same issue.
Im trying to update a distribution list by sending a put request, when I run this code and test it in postman by giving it a JSON body I get this error in my node.js terminal stating SyntaxError: Unexpected end of JSON input ... any idea what I should change?
My PUT API request
app.put("/api/Dls/Add/:groupId" , (req, res) => {
const response = {
success: false
};
if (Authorized.myToken) {
response.success = true;
response.data = {};
var options = {
method: 'PUT',
url: 'https://SomeAPI.com/' + req.params.groupId,
headers:
{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
},
body: JSON.stringify(req.body)
};
request(options, function (error, response, body){
if (error) {
console.log(error);
return;
}
const data = response.body;
const dls = JSON.parse(data)
return res.json(dls);
});
}
});
JSON body I'm passing through postman to test the API call
{
"groupId": "123456789",
"SomeField1": null,
"SomeField2": "xxxxxxxxx",
"SomeField3": true,
"SomeField4": "xxxxxxxxx",
"SomeField5": "xxxxxxxxx",
"SomeField6": [
"xxxxxxxxx"
],
"SomeField7": "xxxxxxxxx",
"SomeField8": "xxxxxxxxx",
"SomeField9": "xxxxxxxxx",
"SomeField10": "xxxxxxxxx",
"SomeField11": [],
"SomeField12": "xxxxxxxxx",
"SomeField13": null,
"SomeField14": false,
"SomeField15": ["xxxxxxxxx"]
}
Any feedback is appreciated!
If the JSON that you posted here is the real one that you pass via postman then, it is not the valid JSON as you have the same name properties. When I say valid it means you get something like this after posting to the endpoint.
{
"groupId": "123456789",
"SomeField": [
"xxxxxxxxx"
]
}
Request npm package is also deprecated so it is better to not use it and replace it with something like Axios. TBH I did not see any error in the code that causes the error that you mentioned, do you have access to the API to check the logs? Maybe something went wrong on the https://SomeAPI.com/ endpoint.
I figured out what the issue was, I needed to add the .end to the return statement
ex. return res.status(200).end()
In my Express app, the response from a POST request to /keepAlive returns an empty JSON. However, when I print in the same variable in the console, I see the value.
This is what I see in the console:
{
status: 'ok',
code: '0',
msg: 'Keepalive procesado correctamente.',
ops: [
op1: {
op: 'upsertuser',
params: [Array],
created: 2019-07-19T16:12:39.000Z
}
]
}
And this is what I see in Postman:
{
"status": "ok",
"code": "0",
"msg": "Keepalive procesado correctamente.",
"ops": []
}
This is my code in Node.js:
app.post('/keepAlive', middleware.checkToken, function(req, res) {
keepAlive(req, res, function(opsvar) {
var json = {
status: 'ok',
code: '0',
msg: 'Keepalive procesado correctamente.',
ops: opsvar
};
console.log(json);
res.status(200).json(json);
})
})
I found my own mistake, the problem was that I initialized the variable opsvar as an array and it had to be initialized as an Object.
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.