Angular Http POST change format value - node.js

I am sending the object message to an API by using POST request on Angular :
//Angular
var message = {
'title':"Test",
'content':"blabla",
'image':"none",
'author':"michael",
'likedBy':['alexis','laura']
};
return this.http.post(this.REST_API_SERVER, message, {headers: new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'})});
Actually my API output show me this :
OUTPUT:
{
'{"title":"Test","content":"blabla","image":"none","author":"michael","likedBy":': { '"alexis","laura"': '' }
}
But I would like this :
{
_id: 5f887c43bee87a1014d89d21,
title: 'Test',
content: 'blabla',
image: 'none',
author: 'michael',
likedBy: [ 'alexis', 'laura' ]
}

You need to change content type to application/json.

Related

Apollo - How to add a dynamic header for subgraph

I am using the #apollo/gateway for a GraphQL implementation.
When implementing a subgraph, the endpoint is an internal DNS record. I have a total of 3 microservices, see below for the code snippet:
const { ApolloGateway, IntrospectAndCompose, RemoteGraphQLDataSource } = require("#apollo/gateway");
const gateway = new ApolloGateway({
supergraphSdl: new IntrospectAndCompose({
subgraphs: [
{ name: "users-api", url: `users.private/graphql?` },
{ name: "cars-api", url: `cars.private/graphql?` },
{ name: "posts-api", url: `posts.private/graphql?` }
],
}),
buildService({ name, url }) {
return new RemoteGraphQLDataSource({
url,
willSendRequest({ request, context }) {
Object.keys(context.headers || {}).forEach(key => {
if (context.headers[key]) {
request.http.headers.set(key, context.headers[key]);
}
});
},
});
},
});
What I am trying to do is sending a custom header to each of the subgraphs. For example:
subgraph users-api, inject header: service=users
subgraph cars-api, inject header: service=cars
Is this possible?
Thanks in advance!

How can i send calendar invitaion and make sure it sit in gmail and outlook calendar using mailgun(node js)?

I am using mailgun(node js) to send an calendar invite, I am able to send invites but it is not adding to calendar automatically.
How we can automate this calendar invite to gmail, outlook calendar?
How can i achieve Yes, Maybe, No or RSVP or accept or reject options for both gmail and outlook using mailgun(node js) using ical-generator, Ex: var ical = require('ical-generator');?
gmail image
outlook image
Hi Robert,
Thanks for the your time and suggestion.
I have tried using the similar .ics file which gamil gives but it really didn't work to auto sync to calendar or "Yes", "No", "May be" options.
Here is the other example what i have written and trying auto calendar sync and "Yes", "MayBe", "No"options.
Using node module 'ical-generator'.
var ical = require('ical-generator');
var eventObj = {
'start' : '2022-06-02T06:59:52.653Z',
'end' : '2022-06-02T07:59:52.653Z',
'title': "Test mail",
'subject': 'Hey There, Im testing API',
'description': 'Hi User',
"Content-Type": "text/calendar,method=REQUEST",
"method": "REQUEST",
'url': "<domain>",
'id' : '125756xr378',
'organiser' : {'name' : 'Narendra M', 'email':'narendrahd#example.in'},
'location' : 'USA, main',
organizer: { name: 'Narendra M', email: 'narendrahd#example.in' },
attendees: [
{ name: 'Narendra M', email: 'narendrahd#example.in', rsvp: true, partstat: 'ACCEPTED', role: 'REQ-PARTICIPANT' },
],
};
var cal = ical();
Creation of an event using ical.
cal.createEvent({
start: eventObj.start,
end: eventObj.end,
summary: eventObj.title,
method: eventObj.method,
uid: eventObj.id, // Some unique identifier
sequence: 0,
subject: eventObj.subject,
description: eventObj.description,
'Content-Type': "text/calendar,method=REQUEST",
location: eventObj.location,
organizer: {
name: eventObj.organiser.name,
email: eventObj.organiser.email
},
attendees: [
{ name: 'Narendra M', email: 'narendrahd#example.in', rsvp: true, partstat: 'ACCEPTED', role: 'REQ-PARTICIPANT' },
],
});
var path = __dirname + eventObj.id + '.ics';
cal.saveSync(path);
craetion of request and rest call to run mailgun API
var request = require('request');
var fs = require('fs');
var options = {
'method': 'POST',
'url': 'https://api.mailgun.net/v3/<domain>/messages',
'headers': {
'Authorization': 'Basic <token>'
},
formData: {
'from': 'noreply#dummy.in',
'to': ['narendrahd#example.in', 'iamnotveda#example.com'],
'subject': 'Hey There, Im testing API',
'text': 'Hi User',
// 'html': '\'<html><body><p>Hi User,</p></body></html>\'',
'attachment': [{
//'value': fs.createReadStream('/Users/invite.ics'),
'value': fs.createReadStream(path),
'options': {
'filename': 'invite.ics',
'contentType': "application/ics,method=REQUEST"
}
},
]
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
Thanks in advance.
Narendra
I suspect partstat: 'ACCEPTED' for attendee could be a culprit here, consider changing it to 'NEEDS-ACTION'.
I recommend checking out this answer which doesn't use ical-generator. Export the raw iCal file and compare the output.

Unknown name "time_to_live" at 'message':

I am trying to send push notification via firebase:
await admin.messaging().sendAll({
token: 'some token',
data: {val1: '1', val2: '2'},
time_to_live: 300,
});
I am getting next error:
{"message":"Send push notification failed, Invalid JSON payload
received. Unknown name "time_to_live" at 'message': Cannot find
field.","level":"error"}
In firebase for time_to_live the key is ttl, also I use this request body for sending push notifications in android apps:
const body = {
notification: {
title: 'xxxx',
body: "xxxxxxxx"
},
data: {
notification_message: "xxxxxx"
},
token: 'xxxxxx',
android: {
ttl: 3600,
notification: { icon: 'xxxxx', color: '#b2b2b2' }
}
}
await admin.messaging().send(body)
Use ttl key in case of time_to_live.

Node breaks JSON string in URL on 'equal' sign =

I am receiving user object from FB API on a React client (localhost:3000).
Then i'm sending it to my node server (localhost:4000)
When the object is received on the node route and i console log it, it SPLITS any value that has '=' sign to ': ' (colon and space). That's breaking my JSON object.
original object being sent from client: (problem is in imageUrl key equal signs)
userInfo {
about: "abcde"
age: 26
email: "test#test.com"
fbProfileLink: "www.some-profile-link-here.com"
gender: "male"
id: null
imageUrl: "https://url-url.url.url/platform/profilepic/?asid=3422352323&height=50&width=50&ext=3422352323&hash=hash"
language: {mainLang: "", speaksEnglish: true}
name: "abcde"
residence: "abcde"
}
This is how i get it in the node server: (turns to 'asid': ...)
"imageUrl":"https://url-url.url.url/url/profilepic/?asid': '3422352323',
height: '50',
width: '50',
ext: '3422352323',
hash: 'hash'
router function:
router.post("/post-test", (req, res, next) => {
console.log("hi amit POST")
console.dir(req.body)
res.end()
})
request sending from client:
axios.post("http://localhost:4000/post-test", user, {
headers: {"Content-Type": "application/x-www-form-urlencoded"}
})
.then(res => {})
.catch(err => {
console.log(err)
})
its like its breaking the string to query params but i just want it as a string
axios.post("http://localhost:4000/post-test", user, {
headers: {"Content-Type": "application/x-www-form-urlencoded"}
})
Here, you are telling the server that you are sending form-urlencoded data. URL-encoded data follows the key=value&key2=value2 format. The server sees the Content-Type header and tries to parse your JSON as URL-encoded data.
Change the Content-Type to the JSON one:
axios.post("http://localhost:4000/post-test", user, {
headers: {"Content-Type": "application/json"}
})
You are sending an incorrect header which is causing the server to parse the values incorrectly.
Change
{"Content-Type": "application/x-www-form-urlencoded"}
to
{"Content-Type": "application/json"}
I'm Assuming you're using express with body parser.
In order to make it work with json, consider bootstrapping your app in the following way:
Server
const express = require("express")
const bodyParser = require('body-parser')
const app = express();
app.use(bodyParser.json());
Client
axios.post("http://localhost:4000/post-test", user, {
headers: {"Content-Type": "application/json"}
});
Payload
{
"about": "abcde",
"age": 26,
"email": "test#test.com",
"fbProfileLink": "www.some-profile-link-here.com",
"gender": "male",
"id": null,
"imageUrl": "https://url-url.url.url/platform/profilepic/?asid=3422352323&height=50&width=50&ext=3422352323&hash=hash",
"language": {
"mainLang": "",
"speaksEnglish": true
},
"name": "abcde",
"residence": "abcde"
}
Result
hi amit POST
{ about: 'abcde',
age: 26,
email: 'test#test.com',
fbProfileLink: 'www.some-profile-link-here.com',
gender: 'male',
id: null,
imageUrl:
'https://url-url.url.url/platform/profilepic/?asid=3422352323&height=50&width=50&ext=3422352323&hash=hash',
language: { mainLang: '', speaksEnglish: true },
name: 'abcde',
residence: 'abcde' }

JSON response: Node server and Sencha

I'm struggling to understand why I don't get anything in the Sencha view. I believe there is an issue with the json transferred between a server and the Sencha proxy. I have a server coded in node and express and a proxy reader in Sencha. But Sencha cannot read the data.
Server Side:
app.get('/weather/fulljson',function(req, res) {
var obj = {data: [{ from_user: 'world', data: 'inter' }, { from_user: 'world2', data: 'interw' }, { from_user: 'world3', data: 'interw' }]};
jsonP = false;
var cb = req.query.callback;
console.log(cb);
if (cb != null) {
jsonP = true;
res.writeHead(200, {
'Content-Type': 'text/javascript',
'connection' : 'close'
});
} else {
res.writeHead(200, {'Content-Type': "application/x-json"});
}
if (jsonP) {
res.end(cb + "(" + JSON.stringify(obj) + ");" );
}
else { res.end(JSON.stringify(obj));
}
)};
});
Sencha View:
Ext.define('Epic.view.Weather', {
xtype: 'graph',
extend: 'Ext.DataView',
//requires: ['Epic.store.SWeather'],
requires: ['Epic.model.MWeather', 'Ext.data.proxy.JsonP'],
config: {
store: {
autoLoad: true,
fields: ['from_user', 'data'],
proxy: {
type: 'jsonp',
url: 'http://localhost:3000/weather/fulljson',
reader: {
type: 'json',
rootProperty: 'data'
}
}
}
},
itemTpl: '{from_user}'
});
Response in Chrome:
Ext.data.JsonP.callback1({"data":[{"from_user":"world","data":"inter"},{"from_user":"world2","data":"interw"},{"from_user":"world3","data":"interw"}]});
But nothing appear in the view.
Did you check your store after load? is it contains data that you send? If yes - in that case something wrong with your view. You can use debugger tools and get your component and check store.
Also could you shows your model Epic.model.MWeather ? Actually if you have model, you don't have to add fields to your store.

Resources