I am attempting to use the nativescript HTTP.request to send a curl for firebase push notifications. I have tested the curl and it works however I am getting a bad request error when i try to send it via http.request.
Here is the curl code (my key has been substituted for a variable for privacy reasons)
curl -X POST --header "Authorization: key=MyKey" --Header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d "{\"notification\":{\"title\": \"My title\", \"text\": \"My text\", \"sound\": \"default\"}, \"data\":{\"foo\":\"bar\"}, \"priority\": \"High\", \"to\":\"d1LHpypPxA0:APA91bHG4HlZQnb7F_BkZAZYHv1MM00FhNbsONMhsLRB-U4p3As3C0Pp_8ALqQFusOOkgdSHZUlOfHbtt6qXU8pzCnjC-ozfMU3vTqjY0iy90XDvGHkDt0qw1w2wnr73PjFqViHEGONH\"}"
here is my http.request
http.request({
url: 'https://fcm.googleapis.com/fcm/send',
method: "POST",
headers: { 'Authorization': 'key=MyKey','Content-Type': 'application/json'} ,
content: {
"notification": {
"title": "testingtesting",
"text": "some text",
"sound": "default",
"priority": "High"
}
},
data: { "foo": "bar" },
to: "d1LHpypPxA0:APA91bHG4HlZQnb7F_BkZAZYHv1MM00FhNbsONMhsLRB-U4p3As3C0Pp_8ALqQFusOOkgdSHZUlOfHbtt6qXU8pzCnjC-ozfMU3vTqjY0iy90XDvGHkDt0qw1w2wnr73PjFqViHEGONH"
}).then((response) => {
//HttpResult = response.content.toJSON();
console.log('----------------------------------------------------');
console.log(response.content);
}, (e) => {
console.log("Error occurred " + e);
});
any help would be greatly appreciated!
I figured it out, this is the code that worked. I had some issues with formatting, I hope this helps someone in the future!
var HttpResult;
http.request({
url: 'https://fcm.googleapis.com/fcm/send',
method: "POST",
headers: { 'Authorization': 'key=MyKey', 'Content-Type': 'application/json' },
content: JSON.stringify({
"notification": {
"title": "testingtesting",
"text": "some text",
"sound": "default",
"priority": "High"
},
'data': { "foo": "bar" },
'to': "d1LHpypPxA0:APA91bHG4HlZQnb7F_BkZAZYHv1MM00FhNbsONMhsLRB-U4p3As3C0Pp_8ALqQFusOOkgdSHZUlOfHbtt6qXU8pzCnjC-ozfMU3vTqjY0iy90XDvGHkDt0qw1w2wnr73PjFqViHEGONH"
})
}).then((response) => {
//HttpResult = response.content.toJSON();
console.log('----------------------------------------------------');
console.log(JSON.stringify(response));
}, (e) => {
console.log("Error occurred " + JSON.stringify(e));
});
Related
I need to create records in an airtable base and have the following code in scrapy:
url = "https://api.airtable.com/v0/appuhKmlhLIIEszLm/Table%201"
payload = json.dumps({
"records": [
{
"fields": {
"Name": "Temporada 6"
}
},
{
"fields": {
"Name": "Temporada 2"
}
}
]
})
headers = {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
}
yield scrapy.Request(method = "POST",url = url, headers=headers, body=payload)
I checked the code with python requests and works, however, when I use this scrapy code, no info is uploaded, do you know why is this?
describe('Getting asset for player', () => {
before(() => {
return provider.addInteraction({
given: 'GET call',
uponReceiving: 'Get asset for player',
withRequest: {
method: 'GET',
path: term({
matcher: '/api/assets/[0-9]+',
generate: '/api/assets/10006'
}),
},
willRespondWith: {
status: 200,
headers: { 'Content-Type': 'application/json' },
body: assetByPlayer
}
});
});
it('Get the asset by player', () => {
return request.get(`http://localhost:${PORT}/api/assets/10006`)
.set({ 'Accept': 'application/json' }).then((response) => {
return expect(Promise.resolve(response.statusCode)).to.eventually.equals(200);
}).catch(err => {
console.log("Error in asset with player listing", err);
});
});
});
I get the json file as : https://pastebin.com/TqRbTmNS
When i use the json file in other code base by pact stub server , it
gets the request from UI as
===> Received Request ( method: GET, path: /api/assets/10006, query:
None, headers: Some({"actasuserid": "5", "content-type": "application/vnd.nativ.mio.v1+json", "host": "masteraccount.local.nativ.tv:30044", "accept": "application/json", "authorization": "Basic bWFzdGVydXNlcjptYXN0ZXJ1c2Vy", "connection": "close", "content-length": "2"}), body: Present(2 bytes) )
but does not sends any response
But if i just remove the matching rules part
"matchingRules": {
"$.path": {
"match": "regex",
"regex": "\/api\/assets\/[0-9]+"
}
}
it starts to work again
===> Received Request ( method: GET, path: /api/assets/10006, query: None, headers: Some({"authorization": "Basic bWFzdGVydXNlcjptYXN0ZXJ1c2Vy", "accept": "application/json", "content-length": "2", "connection": "close", "host": "masteraccount.local.nativ.tv:30044", "content-type": "application/vnd.nativ.mio.v1+json", "actasuserid": "5"}), body: Present(2 bytes) )
<=== Sending Response ( status: 200, headers: Some({"Content-Type": "application/json"}), body: Present(4500 bytes) )
and I can see the data to be present
Could you let me what is wrong here ?
I am using nock to mock my asynchronous thunk action creators. Everything works as expected for GET requests, but I haven't been able to make a POST request work. I have read everything I can find online but nothing fixed my problem. I can see the response body in the failed test run. The issue is that there is no nock match for the url. Can anyone spot the problem?
Test file:
describe('#saveReminder', () => {
it(`creates ${constants.actions.REQUEST_SAVE_REMINDER}
and ${constants.actions.RECEIVE_SAVE_REMINDER}`, () => {
data = { payload: 'payload' };
nock(constants.paths.API_AUTHORITY)
.post('api/prospect/add-reminder', {
prospect: 1,
reminder_datetime: '2017-12-22T18:42:00.000Z',
description: 'description',
})
.reply(200, { data } )
const expectedActions = [
{ type: constants.actions.REQUEST_SAVE_REMINDER },
{ type: constants.actions.RECEIVE_SAVE_REMINDER, data }
]
return store.dispatch(actions.saveReminder({
id: 1,
description: 'description',
date: moment(),
time: moment(),
})).then(() => {
expect(store.getActions()).toEqual(expectedActions)
})
})
})
Async action:
export function saveReminder({ id, description, date, time }) {
return (dispatch) => {
requestSaveReminder();
return fetch(`${constants.paths.API_AUTHORITY}api/prospect/add-reminder`, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-Csrf-Token': Cookie.get('X-Csrf-Token'),
},
credentials: 'same-origin',
method: 'POST',
body: JSON.stringify(
{
prospect: id,
reminder_datetime: moment(`${date.format('MM/DD/YYYY')} ${time.format('HH:mm')}`, 'MM/DD/YYYY HH:mm'),
description,
}
),
}).then(response => {
response.json();
})
.then(json => dispatch(receiveSaveReminder(json.data)))
.catch(ex => dispatch(requestSaveReminderFailure(ex)));
};
}
Test Failure:
Object {
- "type": "REQUEST_SAVE_REMINDER",
+ "data": [FetchError: request to http://localhost:8080/api/prospect/add-reminder failed, reason: Nock: No match for request {
+ "method": "POST",
+ "url": "http://localhost:8080/api/prospect/add-reminder",
+ "headers": {
+ "accept": [
+ "application/json"
+ ],
+ "content-type": [
+ "application/json"
+ ],
+ "accept-encoding": [
+ "gzip,deflate"
+ ],
+ "user-agent": [
+ "node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"
+ ],
+ "connection": [
+ "close"
+ ],
+ "content-length": [
+ 89
+ ]
+ },
+ "body": "{\"prospect\":1,\"reminder_datetime\":\"2017-12-22T18:56:00.000Z\",\"description\":\"description\"}"
+ }],
+ "type": "REQUEST_SAVE_REMINDER_FAILURE",
},
- Object {
- "data": Object {
- "payload": "payload",
- },
- "type": "RECEIVE_SAVE_REMINDER",
- },
The urls appear to match. Why does it say Nock: No match for request? Thanks!
Because you are not only matching URLs, you are also validating expected payload with Nock. If you replace your nock post() call with .post('api/prospect/add-reminder', () => true) I would think the timestamp difference wont affect you.
Is there a way to send push notification directly from an Android app by making POST requests directly to https://fcm.googleapis.com/fcm/send ? If so, can you please provide an example.
If you can read JavaScript, check the simple-fcm-client example on react-native-fcm. Specifficaly, the FirebaseClient.js file
I'll post the code here for completeness, but you need to replace token with the destined device's registered token and FirebaseConstants.KEY with your API Web key from your Firebase console.
const API_URL = "https://fcm.googleapis.com/fcm/send";
class FirebaseClient {
constructor() {
this.sendData = this.sendData.bind(this);
this.sendNotification = this.sendNotification.bind(this);
this.sendNotificationWithData = this.sendNotificationWithData.bind(this);
}
sendNotification(token) {
let body = {
"to": token,
"notification":{
"title": "Simple FCM Client",
"body": "This is a notification with only NOTIFICATION.",
"sound": "default",
"click_action": "fcm.ACTION.HELLO"
},
"priority": 10
}
this._send(JSON.stringify(body), "notification");
}
sendData(token) {
let body = {
"to": token,
"data":{
"title": "Simple FCM Client",
"body": "This is a notification with only DATA.",
"sound": "default",
"click_action": "fcm.ACTION.HELLO",
"remote": true
},
"priority": "normal"
}
this._send(JSON.stringify(body), "data");
}
sendNotificationWithData(token) {
let body = {
"to": token,
"notification":{
"title": "Simple FCM Client",
"body": "This is a notification with NOTIFICATION and DATA (NOTIF).",
"sound": "default",
"click_action": "fcm.ACTION.HELLO"
},
"data":{
"title": "Simple FCM Client",
"body": "This is a notification with NOTIFICATION and DATA (DATA)",
"click_action": "fcm.ACTION.HELLO",
"remote": true
},
"priority": "high"
}
this._send(JSON.stringify(body), "notification-data");
}
_send(body, type) {
let headers = new Headers({
"Content-Type": "application/json",
"Content-Length": parseInt(body.length),
"Authorization": "key=" + FirebaseConstants.KEY
});
fetch(API_URL, { method: "POST", headers, body })
.then(response => console.log("Send " + type + " response", response))
.catch(error => console.log("Error sending " + type, error));
}
}
I am trying to share a post on linkedin.
I managed to log in and get returned an id and an accessToken but when I follow the REST APIs way of sharing an update I keep getting:
Error: failed [400] {
"errorCode": 0,
"message": "Can not parse JSON share document.\nRequest body:\n\nError:\nnull",
"requestId": "NWGE7D4LSW",
"status": 400,
"timestamp": 1451699447711
}
My http POST looks like this:
HTTP.post('https://api.linkedin.com/v1/people/~/shares?format=json&oauth2_access_token=' + accessToken, {
'headers': {
'Content-Type': "application/json",
'x-li-format': "json"
},
'comment': "test!",
'visibility': {
'code': "anyone"
}
});
this worked:
HTTP.post('https://api.linkedin.com/v1/people/~/shares?format=json&oauth2_access_token=' + Meteor.user().services.linkedin.accessToken, {
headers: {
"Content-Type": "application/json",
"x-li-format": "json"
},
data: {
comment: "testing",
visibility: {
code: "anyone"
}
}
});