send header with put request node.js - json

var request=require('request');
var values = [
{
"id": "24",
"kind": "nature",
"data": {}
}
]
request.put("http://localhost:5000/api/article/",values,function (err,data,res) {
res=JSON.parse(res)
console.log(res)
})
I think it's kinda obvious what I'm trying to do here. Can someone please tell me what I'm doing wrong?? If I'm verry far of can someone set me on the right track?

var request = require('request');
var values = [
{
"id": "24",
"kind": "nature",
"data": {}
}
];
request({
method: 'PUT',
url: 'http://localhost:5000/api/article/',
body: values,
json: true,
headers: {
'User-Agent': 'request'
}
}, (err, res, body) => {
// ...
});
See the docs: https://www.npmjs.com/package/request#custom-http-headers

Related

How do i make a POST request to an api in React Native?

I am trying to make a Post request to an api but for some reason i am getting a 400 feedback in the process. Being that i am a beginner at this, i can't really figure out where i am getting it wrong. I understand 400 error has to do with incorrect syntax but i am not sure that is the case here. I also checked out the other related posts but none helped address my problem. I have also read through the documentation over and over again but still can't see where i am making a mistake. I will appreciate if you helped me point out the problem.
myPostRequest(){
var mybody = {
"amount": "5.0",
"currency": "EUR",
"externalId": "6547864",
"payer": { "partyIdType": "MSISDN","partyId": "0977948551"}
}
mybody = JSON.stringify(mybody);
var token = "mytoken";
//POST request
fetch('https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay', {
method: "POST",
headers: {
'Authorization': 'Bearer '+token,
'X-Reference-Id': 'f9b8b0a-XXXXXXXXXX',
'X-Target-Environment': 'sandbox',
'Ocp-Apim-Subscription-Key': '14d2a71dXXXXXXXXX',
},
body: mybody,
})
.then((responseJson) => {
alert(JSON.stringify(responseJson));
console.log(responseJson);
})
.catch((error) => {
alert(JSON.stringify(error));
console.error(error);
});
}
Use axios/apisauce instead of fetch
apisauce example:
import { create } from 'apisauce';
const api = create({
baseURL: `http://example.com`,
});
const response = await api.post('/path/to/', body, { headers });
In your case:
import { create } from 'apisauce';
const api = create({
baseURL: `https://sandbox.momodeveloper.mtn.com`,
});
const response = await api.post(
'/collection/v1_0/requesttopay',
{
"amount": "5.0",
"currency": "EUR",
"externalId": "6547864",
"payer": { "partyIdType": "MSISDN", "partyId": "0977948551" }
},
{
headers: {
'Authorization': 'Bearer ' + token,
'X-Reference-Id': 'f9b8b0a-XXXXXXXXXX',
'X-Target-Environment': 'sandbox',
'Ocp-Apim-Subscription-Key': '14d2a71dXXXXXXXXX',
}
}
);

I want to get Affinity Interest from Google analytics api v4

I put the tracking code of google analytics in my web Application, now i want to get the Interests of the user from Google analytics API, I am using Nodejs, here is my request's code and the JSON response I get.
const dimensions_rows = [{
name: 'ga:interestAffinityCategory'
}, ];
const date_filters = [{
startDate: '7daysAgo',
endDate: 'today',
}];
const req = {
reportRequests: [{
viewId: viewId,
dateRanges: date_filters,
dimensions: dimensions_rows,
}],
};
analytics.reports.batchGet({
auth: oauth2Client,
requestBody: req
},
function(err, response) {
if (err) {
console.log('Failed to get Report');
console.log(err);
return;
}
// response.data is where the good stuff is located
console.log('Success - got something back from the Googlez');
console.log("responseee: ", JSON.stringify(response.data));
}
);
//JSON response
{
"reports": [{
"columnHeader": {
"dimensions": ["ga:interestAffinityCategory"],
"metricHeader": {
"metricHeaderEntries": [{
"name": "ga:visits",
"type": "INTEGER"
}]
}
},
"data": {
"totals": [{
"values": ["0"]
}]
}
}]
}

Render HTTP-Response as a list in Angular2

I have a json response like this.
{
"response": {
"data": {
"customers": [{
"customerNumber": "123",
"customerName": "ABC",
"customeraddresse": [{
"address": "test"
}]
}, {
"customerNumber": "345",
"customerName": "CDS",
"customeraddresse": [{
"address": "test1"
}]
}]
}
}
}
I am doing a request like this to get the response data. And it will be returned, as I already checked.
public getData(): Promise<any> {
let payload = JSON.stringify( ... );
let headers = new Headers({ 'Content-Type': 'application/json'});
return this.http.post(this.url, payload, { headers: headers })
.toPromise()
.then(res => {
this.response_data = res.json().response.data;
return this.response_data;
})
.catch(this.handleError);
}
But the problem is, that I want to get the value of customerNumber and customerName, and display them in a list
In this example, there are two customers, so this markup should be rendered two times:
<div>
<div>CustomerNumber</div>
<div>CustomerName</div>
</div>
You should use an *ngFor loop.
In your template:
<div *ngFor="let customer of response_data.customers">
<div>{{customer.customerNumber}}</div>
<div>{{customer.customerName}}</div>
</div>

Angular2, get data from REST call

I'm triyng to get data from json file by a id, by I'm getting all the content.
Here the JSON:
[
{ "id": "1", "name": "Carlos", "apellidos":"López", "edad":"30", "ciudad":"Hospitalet" },
{ "id": "2", "name": "Arantxa", "apellidos":"Pavia", "edad":"24", "ciudad":"Barcelona" },
{ "id": "3", "name": "Didac" , "apellidos":"Pedra", "edad":"muchos", "ciudad":"Cornellà" },
{ "id": "4", "name": "Daniel" , "apellidos":"Farnos", "edad":"nolose", "ciudad":"Barcelona" }
]
Service:
private usersUrl = 'app/users.json';
getUser(id: String): Observable<User>{
let body = JSON.stringify(
{
"token": "test",
"content": {
"id": id
}
}
);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({
headers: headers,
body : body
});
return this.http.get(this.usersUrl, options)
.map(res => res.json()).catch(this.handleError);
}
Angular Component:
ngOnInit(){
this.route.params.subscribe(params => {
let id = +params['id'];
this.apiService.getUser(id).subscribe( (res) => { console.log(res); } );
})
}
Console.log:
Array[4]0: Object1: Object2: Object3: Objectlength: 4__proto__: Array[0]
Is the JSON bad?
Thanks.
Because you didn't filter the result by id.
.map(res => res.json())
.map(x > x.find(x => x.id == id) // filter by selected id
.catch(this.handleError);

Send emails using Sendgrid with google appscript

I am creating a googlesheet addon to send mails.And for sending mails I am using sendgrid.
I cannot find any documentation or example code for sending mails with Google Appscript. This is the code I am using, but it is no good.
var data = {
"api_user":"username",
"api_key":"ioioi",
"to":[],
"tonnage":[],
"cc":[],
"ccname":[],
"bcc":[],
"subject":sub,
"from":from,
"html":htmlBody
}
var headers = { "Accept":"application/json",
"Content-Type":"application/json"
};
data = JSON.stringify(data);
var options = {
"method": "POST",
"payload": data,
"headers": headers,
"muteHttpExceptions": true
};
var res = UrlFetchApp.fetch("https://api.sendgrid.com/api/mail.send.json", options);
Does anyone have any idea or code to send emails with sendgrid using googl appscript?
Try the below code. It worked for me
var SENDGRID_KEY ='Your API KEY';
var headers = {
"Authorization" : "Bearer "+SENDGRID_KEY,
"Content-Type": "application/json"
}
var body =
{
"personalizations": [
{
"to": [
{
"email": "email id of the sender"
}
],
"subject": "Hello, World!"
}
],
"from": {
"email": "From email id"
},
"content": [
{
"type": "text",
"value": "Hello, World!"
}
]
}
var options = {
'method':'post',
'headers':headers,
'payload':JSON.stringify(body)
}
var response = UrlFetchApp.fetch("https://api.sendgrid.com/v3/mail/send",options);
Logger.log(response);
Also ensure that the API key you created in SendGrid has the all the credentials it needs to send the email
For anyone who has this issue in the future with Transactional Email Template:
https://sendgrid.com/docs/ui/sending-email/how-to-send-an-email-with-dynamic-transactional-templates/
This is the function to send (similar to the answer of Nikil Mathew, but for transactional email template with dynamic data):
export const sendBySendGrid = (toEmail, templateId, dynamicTemplateData) => {
const headers = {
Authorization: `Bearer ${process.env.SENDGRID_API_KEY}`,
'Content-Type': 'application/json',
}
const body = {
from: {
email: process.env.SENDGRID_FROM_EMAIL,
name: process.env.SENDGRID_FROM_NAME,
},
personalizations: [
{
to: [
{
email: toEmail,
},
],
dynamic_template_data: dynamicTemplateData,
},
],
template_id: templateId,
}
const options = {
method: 'POST',
headers,
payload: JSON.stringify(body),
}
const response = UrlFetchApp.fetch('https://api.sendgrid.com/v3/mail/send', options)
Logger.log(response)
}
You can update process.env.SENDGRID_API_KEY, process.env.SENDGRID_FROM_EMAIL, process.env.SENDGRID_FROM_NAME with your SendGrid credentials
Here's what's working for me right now in Google Apps Script, including using a dynamic template and insertion of dynamic data for the "handlebars" in my SendGrid template:
var SENDGRID_KEY ='API_KEY';
var headers = {
"Authorization" : "Bearer "+SENDGRID_KEY,
"Content-Type": "application/json"
}
function sendEmail_1() {
var body = {
"personalizations": [
{
"to": [
{
"email": "test#test.com",
"name": "Test Name"
}
],
"bcc": [
{
"email": "test#test.com"
}
],
"dynamic_template_data":
{
"firstName": "Marco Polo"
}
}
],
"from":
{
"email": "test#test.com",
"name": "Test Name"
},
"reply_to": {
"email": "test#test.com"
},
"template_id":"TEMPLATE_ID"
}
var options = {
'method':'post',
'headers':headers,
'payload':JSON.stringify(body)
}
var response = UrlFetchApp.fetch("https://api.sendgrid.com/v3/mail/send",options);
}