I'm trying to used the rest API of firebase with react native. I'm trying to used the notification request but my fetch doesn't work .
I have an error like that :
Possible Unhandled Promise Rejection (id: 10):
SyntaxError: JSON Parse error: Unexpected EOF
i also console.log the response i get this :
{"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "1223679F-6B8F-4104-9085-060585EDF71E", "name": "1.1", "offset": 0, "size": 0, "type": "text/html"}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "1223679F-6B8F-4104-9085-060585EDF71E", "name": "1.1", "offset": 0, "size": 0, "type": "text/html"}}, "bodyUsed": false, "headers": {"map": {"alt-svc": "h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"", "content-length": "0", "content-type": "text/html", "date": "Tue, 06 Apr 2021 14:20:39 GMT", "server": "scaffolding on HTTPServer2", "x-content-type-options": "nosniff", "x-frame-options": "SAMEORIGIN", "x-xss-protection": "0"}}, "ok": false, "status": 404, "statusText": undefined, "type": "default", "url": "https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send%20HTTP/1.1"}
this is my fetch and i call him on the componentdidmount of my app.js
Notif = async () => {
const headers = new Headers({
'Content-type': 'application/json',
Authorization: 'Bearer ' + (await AsyncStorage.getItem('token')),
message:{
token:"ff_Zolz1s0mmgrovad27JG:APA91bHlV5bAXyNHI3aWGyjltdgmJP8mmGBlEC0mPBA72IIJGqoliH4gm1rCQp0szQ5JypKxNhcWcKb7JrOwUTZDmaCB02y4dS553WVDdsxbWuLeK7cqoMjTRjFtFfdMb8bVGxO65BTq",
notification:{
body:"This is an FCM notification message!",
title:"FCM Message"
}
}
});
const options = {
method: 'POST',
headers: headers,
};
fetch('https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1', options)
.then((response) => {
console.log(response);
return response.json();
})
.then(
(err) => {
console.log(err);
},
);
};
Firstly you are handling the fetch request incorrectly as it is missing a catch clause. Secondly, check the url you are sending in the request as it seems to not be properly formatted as a string.
Side note you could await the fetch function since you already made the Notfi function asynchronous and surround this with a try/catch block.
Related
I would like to send a request with a random value or using the current date in the json payload of the request's body in Blazemeter
Example:
method: POST
url: ${url}/transaction
headers:
Content-Type: application/json
body: {
"order": {
"id": uuidGenerator() + "test" ,
"timestamp": datetime( now() , 'yyyy/MM/DDTHH:mm:ssZ')
}
}
Doc references Test Data Generator Functions:
https://guide.blazemeter.com/hc/en-us/articles/360011769877-Test-Data-Generator-Functions-Test-Data-Generator-Functions
Expected
"order": {
"id": "7d052488-6fbf-11eb-9439-0242ac130002-test" ,
"timestamp": "2021-01-15T18:00:00Z"
}
But
id value is not interpreted "uuidGenerator() + "test"
syntax seems to be incorrect for timestamp and card in Blazemter taurus
method: POST
url: ${url}/transaction
headers:
Content-Type: application/json
body: {
"order": {
"id": "${__UUID()}" ,
"timestamp": "${__time(yyyy-MM-dd'T'HH:mm:ss'Z',)}"
}
}
more functions: https://jmeter.apache.org/usermanual/functions.html#__time
Using pact to verify if the response header matches for the consumer and provider.
Running the pact verification on the provider side gives me the following error:
Failure/Error: expect(header_value).to match_header(name, expected_header_value)
Expected header "abc" to equal "xyz", but was nil
However, when I inspect if my response header, it gives me the expected value ("xyz").
Here is the sample pact file I'm trying to verify:
"interactions": [
{
"description": "a request to do something",
"request": {
"method": "get",
"path": "/example"
},
"response": {
"status": 200,
"headers": {
"abc": "xyz"
}
}
}]
I’m new to pact. Any help would be appreciated.
While this is an old post, I hope this will help anyone who views this.
I'm not familiar with ruby, however if your using a basic HTTP Rest request you need to add the accept headers on the 'withRequest' as well as the expected headers on the 'withRespondWith'. You can use Postman to view both request and response headers; JavaScript Example:
describe('When a request is made to get all <resources>', () => {
beforeAll(() =>
provider.setup().then(() => {
provider.addInteraction({
uponReceiving: 'a request to receive to receive all...',
withRequest: {
method: 'GET',
path: '/<resource>',
// Default headers from Axios documentation
headers: { Accept: "application/json, text/plain, */*" }
},
...
willRespondWith: {
// expected headers
headers: { "Content-Type": "application/json; charset=utf-8" },
...
I'm developing a Firefox Add-on, i'm failing to send request from popup script. it is showing some error
Error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource
In chrome extension working fine.
Popup script
$.ajax({
url: 'http://localhost/api/user/66f041e16a60928b05a7e228a89c3799/emailtemplate/c60d870eaad6a3946ab3e8734466e532',
type: 'GET',
dataType: 'json',
headers: { 'accessToken': 'Krc7YPoZPaYiy37O', 'appID': '28fdd9c013e37bca7dd875b10817b694', 'appSecret': '15798907115476fdf1de7a8' },
success: function(eventSettingsResponse) {
buildTemplate(eventDetailsResponse, eventSettingsResponse);
console.log('This is content script testing...', eventDetailsResponse);
},
error: function() { }
//beforeSend: setHeader
});
Package.json
{
"title": "First",
"name": "test",
"version": "0.0.1",
"description": "Just for testing",
"main": "index.js",
"author": "Bharath",
"engines": {
"firefox": ">=38.0a1",
"fennec": ">=38.0a1"
},
"permissions": {
"cross-domain-content": ["http://localhost/*"]
},
"license": "MIT"
}
Main.js
pageMod.PageMod({
include: ["https://mail.google.com/*"],
contentScriptFile: data.url("js/content.js"),
contentScriptWhen: 'end',
onAttach: function(worker) {
worker.port.emit("init", urls);
worker.port.on("showPopup", function() {
console.log('port received');
windows.open(data.url('popup/popup.html'), {
name: 'jetpack window',
features: {
width: 500,
height: 500,
popup: false
}
});
});
worker.port.on("returnHtml", function() {
console.log('Html returnde.');
});
}
});
I read here that I could add the following to package.json
"permissions": {
"cross-domain-content": ["https://data.com"]
}
Using loopback, I have created a connection to an existing API using the REST connector, which is working well. I would however like to pass through the oAuth token coming from the client.
I can get hold of the oAuth token by grabbing ctx.req.headers.authorization from the Model.beforeRemote method, but can't seem to figure out a way of passing it to the REST connector as a new header.
I've tried a couple of things:
Adding a hook using Model.observe (but this doesn't seem to fire with the REST connector).
Using a template with an authorization field - but have not been able to get this working correctly.
Any ideas appreciated.
With the connector below you should be able to pass the OAuth token into the function (as first parameter in the example). Does something like this not work for you?
{
connector: 'rest',
debug: false,
options: {
"headers": {
"accept": "application/json",
"content-type": "application/json",
"authorization": "{oauth}"
},
strictSSL: false,
},
operations: [
{
template: {
"method": "GET",
"url": "http://maps.googleapis.com/maps/api/geocode/{format=json}",
"query": {
"address": "{street},{city},{zipcode}",
"sensor": "{sensor=false}"
},
"options": {
"strictSSL": true,
"useQuerystring": true
},
"responsePath": "$.results[0].geometry.location"
},
functions: {
"geocode": ["oauth", "street", "city", "zipcode"]
}
}
]}
Wanted to answer this, and build on Bryan's comments. Firstly, in datasources.json, you'll want to setup the REST connector:
{
"name": "connect",
"connector": "rest",
"debug": "true",
"operations": [
{
"template": {
"method": "GET",
"url": "http://server/api",
"headers":{
"authorization": "Bearer {token}"
}
},
"functions": {
"get": ["token"]
}
}
]
}
As Bryan covered, it possible to put the auth header in each call, or at the root of the connector.
Secondly, and this is the bit I was stuck on, in order to pass the token to the API call from a model, it's required to generate a remote method that passes the token as a query parameter. This is what it looks like in this example:
module.exports = function (Model) {
Model.disableRemoteMethod('invoke', true);
Model.disableRemoteMethod('get', true);
Model.call = function (req, cb) {
var token = req.token;
Model.get(token, function (err, result) {
cb(null, result);
});
};
Model.remoteMethod(
'call',
{
http: {path: '/', verb: 'get'},
accepts: [
{arg: 'req', type: 'object', http: {source: 'req'}}
],
returns: {
root: true
}
}
);
};
Notice how the req argument is required in order to provide the request to the model. You also notice that I've disabled the original get and invoke methods (replacing it with a more REST-friendly resource).
Finally, you'll need to get the token into the request. For this, it's easy enough to use some middleware. Here's an example from server.js:
app.use('/api', function (req, res, next) {
oidc.authenticate(req, function (err, token) {
if (err) {
return res.send({status: 401, message: err});
}
req.token = token;
next();
});
});
In the above example, I'm using an internal OIDC provider to validate the token, but of course, you can use anything.
I'm using Parse.Cloud.httpRequest and I need to send basic authentication with only a username to balanced payments. Where does this go and what would that look like? I tried setting it in the Headers but that's not working.
Parse.Cloud.httpRequest({
method:'POST',
url: customerUrl,
headers:{
"Content-Type" : "application/x-www-form-urlencoded",
"Accept" : "application/vnd.api+json;revision=1.1",
"Authorization" : balancedSecret
},
body:bodyJsonString,
success: function(httpResponse) {
console.log(httpResponse.text);
response.success(httpResponse.text);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error(httpResponse.text);
}
});
When I call the function I get:
"errors": [
{
"status": "Unauthorized",
"category_code": "authentication-required",
"description": "Not permitted to perform create on customers. Your request id is OHMca9c440a0a7811e4ba9202a1fe52a36c.",
"status_code": 401,
"category_type": "permission",
"request_id": "OHMca9c440a0a7811e4ba9202a1fe52a36c"
}
]
"Authorization" : balancedSecret
This is going to be wrong. You use the secret as the username, and nothing as the password. You then concatenate them together, base64 encode them, and pass that as the value of the auth header.
I don't have the setup to double check this, but this should work as the value:
"Basic " + encodeBase64(balancedSecret + ":")
Giving this code:
authHeader = "Basic " + btoa(balancedSecret + ":")
Parse.Cloud.httpRequest({
method:'POST',
url: customerUrl,
headers:{
"Content-Type" : "application/x-www-form-urlencoded",
"Accept" : "application/vnd.api+json;revision=1.1",
"Authorization" : authHeader
},
body:bodyJsonString,
success: function(httpResponse) {
console.log(httpResponse.text);
response.success(httpResponse.text);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error(httpResponse.text);
}
});