Meteor Restivus - POST body (JSON) to mongoDB - javascript

My code looks like this. Its a post action in Restivus.
'subs' is a mongoDB collection.
post: {
authRequired: false,
action: function () {
var tmp = subs.insert(this.bodyParams);
if(tmp){
return tmp;
}
return {
statusCode: 400,
body: {status: 'fail', message: 'Unable to CREATE subscriber!'}
};
}
}
When I send some JSON data in the body, for example:
{
_id: 1,
name: "John",
lastname: "Smith"
}
In the mongoDB a new document is created, but with just some random (default notation) string and without the data I sent. So I guess the data is not parsed right.
Does anyone know why this happens? Should I do some function to format the JSON before passing it to mongoDB from the body?

Try this ... insert {status: 'success', data: tmp};.
post: {
authRequired: false,
action: function () {
var tmp = subs.insert(this.bodyParams);
if(tmp){
return {status: 'success', data: tmp};
}
return {
statusCode: 400,
body: {status: 'fail', message: 'Unable to CREATE subscriber!'}
};
}
}

The problem was with sending requests from Postman (Google Chrome addon). When I used curl it worked!

Related

my api is returning invalid JSON nodejs in post request while fectching

I am sending a post request in my next js app API (API is for updating address)
this is my fetching API code
async function handleSubmit() {
const data = { deliveryAddress, landmark, pincode, district, block, state }
const userID = localStorage.getItem("userID")
for (let item in data) {
let element = data[item];
if (element == "") {
toast.error(`${item} field must be filled`, {
position: "top-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined
});
break;
}
}
console.log("above try");
console.log({ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify( userID)) });
try {
console.log("hello");
let res = await fetch(`${process.env.NEXT_PUBLIC_HOST}/api/updateaddress`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: [{ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify(userID)) }]
})
let parsedResponse = await res.json()
console.log("response", parsedResponse);
}
catch (error) {
console.log(error)
}
}
and this code is returning an invalid Json error
this code line body: [{ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify(userID)) }]
this is what I got when I console.log my response body console.log({ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify( userID)) });
image of console error and the above-logged coder
Summary
I am getting a invalid JSON error but i think my JSON is correct and nothing wrong with api
I am getting a invalid JSON error
Well, your JSON is invalid…
body: [{ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify(userID)) }]
That's an array, not JSON. You need to pass JSON to the body property.
Also JSON.parse(JSON.stringify(...)) does nothing useful in this context (since it is useful to deep clone simple objects and you don't mutate the value afterwards) so don't do that.
body: JSON.stringify([{ "address": data, "userid": userID }])
… but a 401 status means Unauthorized.

rescuegroup/Petfinder jQuery API requests

I am currently trying to get API responses from the two following API's. All of the sample code on their website is in PHP and asks for a token and token SSH, while they only give you an API key. Very lost trying to get requests to pull. The closest I've gotten is an error that says the following:
{status: "error", message: "Unable to read your data; it might not be in json format."}
here is my JS:
jQuery.get({
url: 'https://api.rescuegroups.org/http/v2.json',
type: 'post',
contentType: 'application/json',
data: {
apikey: 'XXXXXXX',
objectType:'animals',
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
Any help is greatly appreciated. Really want to avoid having to learn PHP as I'm still very new to JS.
the problem is that you are not passing it as json.
this is json format.
let dataObject = {
data: {
apiKey: "xxxx"
}
};
let data = JSON.stringify(dataObject);
{
"data": {
"apikey": "xxx"
}
}
then pass data as your data.
After trying it with Postman the request went through.
Obviously I don't have the api key
{
"status": "error",
"message": "Error with your login credentials",
"messages": {
"generalMessages": [
{
"messageID": "1101",
"messageCriticality": "error",
"messageText": "Error with your login credentials."
}
],
"recordMessages": []
}
}

Gmail API messages.get not returning expected data

I'm trying to write an embedded gmail client and have been following through the API documentation on the developer site, but I am unable to get message data in my response. I am able to list labels no problem (using the code from the API docs) so I know it is authenticating ok. I am also able to get message IDs.
When I try to get actual message data, I am running into an issue where the returned Object does not have the data I expect. I check this by logging the messageRequest data to the console because message payload didn't exist when I was initially trying to access it.
function displayInbox() {
var request = gapi.client.gmail.users.messages.list({
'userId': 'me',
'labelIds': 'INBOX',
'maxResults': 10
});
request.execute(function(response) {
$.each(response.messages, function() {
var messageRequest = gapi.client.gmail.users.messages.get({
'userId': 'me',
'id': this.id,
'format': 'full'
});
console.log(JSON.stringify(messageRequest,null,4));
messageRequest.execute(appendPre);
});
});
}
From developer console I get this output:
(index):473 {
"Mq": 1,
"Zq": {
"QT": null,
"k5": {
"path": "/gmail/v1/users/me/messages/15f3a370bc482a7a",
"method": "GET",
"params": {
"format": "full"
},
"headers": {},
"root": "https://www.googleapis.com",
"apiId": "gmail:v1"
},
"Ida": "auto",
"Uja": false,
"Tja": false
}
}
Thanks for any help.
You are currently doing JSON.stringify on the request object. What you are seeing in the console is not the response.
Try and wait for the messageRequest to finish asynchronously, and log the response in the callback instead:
var messageRequest = gapi.client.gmail.users.messages.get({
userId: 'me',
id: this.id,
format: 'full'
});
messageRequest.execute(function(response) {
console.log(response);
});

Node.js/Mongoose/lodash - server response: User Validation Failed: path `foo` is required

The error message being received is:
"User validation failed: email: Path email is required., display_name: Path display_name is required."
The error name being sent back is: ValidationError.
The code for the ajax call is:
function submit_new_user(display_name, email, password){
let user_data = new New_User(display_name, email, password);
console.log(user_data);
$.ajax ({
dataType: 'JSON',
data: user_data,
method:'POST',
url: 'http://localhost:3001/user',
success: (res)=>{
console.log(res);
},
error: (xhr, ajaxOptions, thrownError)=>{
console.log(xhr, ajaxOptions, thrownError);
}
});
};
the console.log seen above prints:
New_User {display_name: "test", email: "test#test.com", password: "Passw0rd"}
The server route is:
app.post('/user', (req, res)=>{
let body = _.pick(req.body, ['display_name', 'email', 'password']);
let user = new User(body);
user.save().then(()=>{
return user.generateAuthToken();
}).then((token)=>{
res.header('x-auth', token).send(user);
}).catch((err)=>{
res.status(400).send(err);
});
});
This route works when pinged with Postman. The server supports cors.
The model is as follows:
var UserSchema = new mongoose.Schema({
display_name: {
type: String,
unique: true,
required: true,
validate: {
validator: (val)=>{
return /^[\w\s]+$/.test(val);
},
message: '{VALUE} is not a valid display name. Only
alphanumeric, upper and lower case characters are allowed.'
}
},
email: {
type: String,
required: true,
unique: true,
validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email.'
}
},
password: {
type: String,
require: true,
minlength: 6
},
tokens: [{
access:{
type: String,
required: true
},
token: {
type: String,
required: true
}
}]
});
I'm still learning node.js. I was guided through the creation of the API, and am trying to build a front end on my own.
The object leaving contains the three value pairs - but the object arriving, before the server changes it, is empty. I'm at loss as to why.
SOLUTION: the problem was in the server-side bodyParser. I had forgotten to include the encoded url method. It was not parsing the JSON as it came in, since previously the API had only been tested using Postman there was no need to use the .urlencoded() method.

Error in Parse Cloud Code with Stripe module in Swift

I am getting this error:
Result: TypeError: Object [object Object] has no method '_each'
at request (stripe.js:58:11)
at post (stripe.js:117:12)
at Object.module.exports.Customers.create (stripe.js:239:16)
at main.js:13:22
This is my swift function call:
let userId = PFUser.currentUser()?.objectId
let userEmail = PFUser.currentUser()?.email
PFCloud.callFunctionInBackground("createCustomer", withParameters: ["email": userEmail!, "objectId": userId!])
This is my cloud code for that specific function:
var Stripe = require('stripe');
Stripe.initialize('sk_test_***************');
Parse.Cloud.define("createCustomer", function(request, response) {
Stripe.Customers.create({
email: request.params.email,
description: 'new Gyro user',
metadata: {
//name: request.params.name,
userId: request.params.objectId, // e.g PFUser object ID
createWithCard: false
}
}, {
success: function(httpResponse) {
response.success(customerId); // return customerId
},
error: function(httpResponse) {
console.log(httpResponse);
response.error("Cannot create a new customer.");
}
});
});
I'm not sure where and why I am getting this error. Any help would be appreciated.

Categories

Resources