Ionic 3 http post - reading body data in nodejs - node.js

I am trying to send a http post body data. It worked well with angular but now I am using ionic. Any help is appreciated.
let newMember = {
"sendData": [{
name: "first_name",
val: "mike"
},
{
name: "last_name",
val: "tester"
},
{
name: "city",
val: "new york"
},
{
name: "state",
val: "NY"
},
{
name: "zip",
val: "10001"
}]
}
let body = new FormData();
body.append('newMember', JSON.stringify(newMember));
this.http.post('https://data.testme.com/setup',newMember,{headers: headers
}, body)
.map(res => res.json())
.subscribe(data => {
console.log(data);
});
}
This is how I am trying to send it to a nodejs server.
My nodejs sever it getting this in the body.
console.log("sendData req.body --> " , req.body);
{sendData: [{
name: 'first_name',
val: 'mike'
},
{
name: 'last_name',
val: 'tester'
},
{
name: 'city',
val: 'new york'
},
{
name: 'state',
val: 'NY'
},
{
name: 'zip',
val: '10001'
}]
}
I found this in my out log. I was looking at my error logs before. Showing error because it could read:
var newMember = req.body.newMember;
How do I read newMember in Node.js ??
Thanks
Phil

You've mismatch parameters. see documentation
try this
this.http.post('https://data.testme.com/setup', body, {
headers: headers
})

and add plugin
Allow-Control-Allow-Origin: *
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
this.http.post(https://data.testme.com/setup/', newMember).map(res => res.json()).subscribe(data => {
console.log('error'+data);
},err => {
console.log('error'+err);
});

Related

Must provide source or customer stripe live mode

this is my first time using stripe and I am getting an error Must provide source or customer. once I went live. In the test mode I used "tok_mastercard" as my source but clearly when I went live it isn't valid. What am I missing here please help.
This is my POST request in the backend
stripe.charges
.create({
amount: req.renter.rent * 100,
currency: "usd",
source: req.body.token,
application_fee_amount: req.renter.rent * 0.05 * 100,
transfer_data: {
//the destination needs to not be hard coded it needs to
//come from what property the renter is in
destination: req.renter.stripeConnectId,
// destination: "acct_1GOCMqDfw1BzXvj0",
},
})
.then((charge) => {
console.log(req.renter);
res.send(charge);
})
.catch((err) => {
console.log(err);
});
});
this is my two functions in the frontend using react-native and node
handleCardPayPress = async () => {
try {
this.setState({ loading: true, token: null });
const token = await stripe.paymentRequestWithCardForm({
// Only iOS support this options
smsAutofillDisabled: true,
requiredBillingAddressFields: "full",
prefilledInformation: {
billingAddress: {
name: "",
line1: "",
line2: "",
city: "",
state: "",
country: "US",
postalCode: "",
email: "",
},
},
});
this.setState({ loading: false, token });
} catch (error) {
this.setState({ loading: false });
}
};
makePayment = async () => {
try {
//Mate the payment
const response = await unitApi.post("/payments", {
data: {
amount: this.state.renter.rent,
currency: "usd",
token: this.state.token,
},
});
Alert.alert("Success!", `Confirmation ID: ${response.data.id}`, [
{ text: "Done" },
]);
console.log(response.data);
// navigate("Home");
} catch (err) {
//failiur and showing the error message
console.log(err);
Alert.alert("Failed!", "Card declined.", [{ text: "Declined" }]);
}
};
Odds are pretty good that this.state.token doesn't contain what you think it does in the unitApi.post() function call; I'd recommend logging that and seeing if that helps, and also logging req.body.token server-side.

Open modal using Slack command

I have a Slack command which displays a button. When I click on this button I need to display a modal. For this, after clicking it I do this:
const dialog = {
callback_id: "submit-ticket",
elements: [
{
hint: "30 second summary of the problem",
label: "Title",
name: "title",
type: "text",
value: "teste"
},
{
label: "Description",
name: "description",
optional: true,
type: "textarea"
},
{
label: "Urgency",
name: "urgency",
options: [
{ label: "Low", value: "Low" },
{ label: "Medium", value: "Medium" },
{ label: "High", value: "High" }
],
type: "select"
}
],
submit_label: "Submit",
title: "Submit a helpdesk ticket"
};
const modalInfo = {
dialog: JSON.stringify(dialog),
token, // this is correct
trigger_id: actionJSONPayload.trigger_id
};
// This is what I get confused with...
// Method 1
slack.dialog.open(modalInfo).catch(err => {
console.log("ERROR: ", err);
});
// end method 1
// Method 2
sendMessageToSlackResponseURL(actionJSONPayload.response_url, modalInfo);
...
function sendMessageToSlackResponseURL(responseURL: any, JSONmessage: any) {
const postOptions = {
headers: {
"Content-type": "application/json"
},
json: JSONmessage,
method: "POST",
uri: responseURL
};
request(postOptions, (error: any, response: any, body: any) => {
if (error) {
console.log("----Error: ", error);
}
});
}
// end method 2
I get always Error: invalid_trigger using method1 when this trigger is something that my button is generating automatically.
Method 2 doesn't throw any error but doesn't open any modal/dialog either.
The official documentation is not quite clear and I don't know if I need to call dialog.open or views.open. Either way, the last one is not available from Slack package
This is also the button I'm displaying before anything:
const message = {
attachments: [
{
actions: [
{
name: "send_sms",
style: "danger",
text: "Yes",
type: "button",
value: "yes"
},
{
name: "no",
text: "No",
type: "button",
value: "no"
}
],
attachment_type: "default",
callback_id: "alert",
color: "#3AA3E3",
fallback: "We could not load the options. Try later",
text: "Do you want to alert by SMS about P1 error/fix?"
}
],
text: "P1 SMSs"
};
Copy a modal from here
const headers = {
headers: {
"Content-type": "application/json; charset=utf-8",
"Authorization": "Bearer " + token
}
};
const modalInfo = {
"token": token,
"trigger_id": reqBody.trigger_id,
"view": slack.modal
};
axios
.post("https://slack.com/api/views.open", modalInfo, headers)
.then(response => {
const data = response.data;
if (!data.ok) {
return data.error;
}
})
.catch(error => {
console.log("-Error: ", error);
});
But most importantly, when we do some changes to our app we need to reinstall it and also when we do it, the token changes and this is something I couldn't find on the documentation

How to insert multiple JSON document in elastic search

Input Data
[{
"_index": "abc",
"_type": "_doc",
"_id": "QAE",
"_score": 6.514091,
"_source": {
"category": "fruits",
"action": "eating",
"metainfo": {
"hash": "nzUZ1ONm0e167p"
},
"createddate": "2019-10-03T12:37:45.297Z"
}},
{
"_index": "abc",
"_type": "_doc",
"_id": "PQR",
"_score": 6.514091,
"_source": {
"category": "Vegetables",
"action": "eating",
"metainfo": {
"hash": "nzUZ1ONm0e167p"
},
"createddate": "2019-10-03T12:37:45.297Z"
}
}-----------------
----------------]
I have around 30,000 records as input data. How to insert this data in a single query. I tried by
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: '********',
log: 'trace'
});
client.index({
index: "abc",
body: ****input data*****
}).then((res) => {
console.log(res);
}, (err) => {
console.log("err", err);
});
In this code, send input data in the body. but it returns an error. Please suggest to me.
This seems like what are you looking for:
'use strict'
require('array.prototype.flatmap').shim()
const { Client } = require('#elastic/elasticsearch')
const client = new Client({
node: 'http://localhost:9200'
})
async function run () {
await client.indices.create({
index: 'tweets',
body: {
mappings: {
properties: {
id: { type: 'integer' },
text: { type: 'text' },
user: { type: 'keyword' },
time: { type: 'date' }
}
}
}
}, { ignore: [400] })
const dataset = [{
id: 1,
text: 'If I fall, don\'t bring me back.',
user: 'jon',
date: new Date()
}, {
id: 2,
text: 'Winter is coming',
user: 'ned',
date: new Date()
}, {
id: 3,
text: 'A Lannister always pays his debts.',
user: 'tyrion',
date: new Date()
}, {
id: 4,
text: 'I am the blood of the dragon.',
user: 'daenerys',
date: new Date()
}, {
id: 5, // change this value to a string to see the bulk response with errors
text: 'A girl is Arya Stark of Winterfell. And I\'m going home.',
user: 'arya',
date: new Date()
}]
// The major part is below:
const body = dataset.flatMap(doc => [{ index: { _index: 'tweets' } }, doc])
const { body: bulkResponse } = await client.bulk({ refresh: true, body })
//
if (bulkResponse.errors) {
const erroredDocuments = []
// The items array has the same order of the dataset we just indexed.
// The presence of the `error` key indicates that the operation
// that we did for the document has failed.
bulkResponse.items.forEach((action, i) => {
const operation = Object.keys(action)[0]
if (action[operation].error) {
erroredDocuments.push({
// If the status is 429 it means that you can retry the document,
// otherwise it's very likely a mapping error, and you should
// fix the document before to try it again.
status: action[operation].status,
error: action[operation].error,
operation: body[i * 2],
document: body[i * 2 + 1]
})
}
})
console.log(erroredDocuments)
}
const { body: count } = await client.count({ index: 'tweets' })
console.log(count)
}
run().catch(console.log)
Reference link: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/bulk_examples.html

searching with elasticsearch js with multiple fields

Hi guys I have this code :
let test = await client.search({
index: 'test',
type: 'doc',
body: {
query: {
match: {
title: 'something',
}
}
}
});
this code is searching by 1 query which is title: 'something' , but I want to change it to search with multiple keys, for example:
let test = await client.search({
index: 'test',
type: 'doc',
body: {
query: {
match: {
title: 'something',
desc: 'some Qualifications'
}
}
}
});
but this code doesn't work and I can't find anything that will work like that, can anyone help?
You need to combine all the match queries using a bool/must query, like this:
let test = await client.search({
index: 'test',
type: 'doc',
body: {
query: {
bool: {
must: [
{
match: {
title: 'something',
}
},
{
match: {
desc: 'some Qualifications',
}
}
]
}
}
}
});

Problem with ottoman not resolving the references

I have two models in my ottoman 1.0.5 setup. One holds contact info which includes an emails array of docs and then the email doc. I can insert new contacts fine as well as emails in docs and the corresponding link in the contact doc for the new email.
Here is my model
const ottoman = require("ottoman")
ottoman.bucket = require("../app").bucket
var ContactModel = ottoman.model("Contact",{
timestamp: {
type: "Date",
default: function() {return new Date()}
},
first_name : "string",
last_name : "string",
emails: [
{
ref:"Email"
}
]} )
var EmailModel = ottoman.model("Email",{
timestamp: {
type: "Date",
default: function() {return new Date()}
},
type : "string",
address : "string",
name: "string"
} )
module.exports = {
ContactModel : ContactModel,
EmailModel : EmailModel
}
Now to get an contact and all its emails i use this function
app.get("/contacts/:id", function(req, res){
model.ContactModel.getById(req.params.id,{load: ["emails"]}, function(error, contact){
if(error) {
res.status(400).json({ Success: false , Error: error, Message: ""})
}
res.status(200).json({ Success: true , Error: "", Message: "", Data : contact})
})
})
Which returns me this
{
"Success": true,
"Error": "",
"Message": "",
"Data": {
"timestamp": "2019-01-30T23:59:59.188Z",
"emails": [
{
"$ref": "Email",
"$id": "3ec07ba0-aaec-4fd4-a207-c4272cef8d66"
}
],
"_id": "0112f774-4b5d-4b73-b784-60fa9fa2f9ff",
"first_name": "Test",
"last_name": "User"
}
}
if i go and log the contact to my console i get this
OttomanModel(`Contact`, loaded, key:Contact|0112f774-4b5d-4b73-b784-60fa9fa2f9ff, {
timestamp: 2019-01-30T23:59:59.188Z,
emails: [ OttomanModel(`Email`, loaded, key:Email|3ec07ba0-aaec-4fd4-a207-c4272cef8d66, {
timestamp: 2019-01-31T00:36:01.264Z,
_id: '3ec07ba0-aaec-4fd4-a207-c4272cef8d66',
type: 'work',
address: 'test#outlook.com',
name: 'Test Outlook',
}),
OttomanModel(`Email`, loaded, key:Email|93848b71-7696-4ef5-979d-05c19be9d593, {
timestamp: 2019-01-31T04:12:40.603Z,
_id: '93848b71-7696-4ef5-979d-05c19be9d593',
type: 'work',
address: 'newTest#outlook.com',
name: 'Test2 Outlook',
}) ],
_id: '0112f774-4b5d-4b73-b784-60fa9fa2f9ff',
first_name: 'Test',
last_name: 'User',
})
This shows that emails was resolved but why does it not show up in the returned json. On the other hand if i return contact.emails i get the resolved emails just fine. So i hope someone can shed some light on what i am missing here
I asked a similar question on the couchbase forum, and I also found out the solution:
(a slight difference that the result of my search is an array not an object like in your case)
forum.couchbase.com
app.get("/assets", (req, res) => {
AssetModel.find({}, { load: ["assetModelId", "assetGroupId", "assetTypeId"] }, (err, results) => {
if (err) return res.status(400).send("no asset found");
const assets = [];
results.map(asset => {
assets.push({...asset});
});
res.status(200).send(assets)
});
});

Resources