I am using web push to enable push notifications for app.
webPush.setGCMAPIKey('my-gcm-api-key');
app.post('/sendNotification', function(req, res) {
console.log(req.body)
payloads[req.body.endpoint] = req.body.payload;
webPush.sendNotification(req.body.endpoint
, {
TTL: req.body.ttl,
}
)
.then(function() {
console.log('mest')
res.sendStatus(201);
})
.catch(function(err){
console.log(err)
});
});
I am getting below error during the sendNotification api call.
{ [WebPushError: Received unexpected response code]
name: 'WebPushError',
message: 'Received unexpected response code',
statusCode: 400,
headers:
{ 'content-type': 'text/html; charset=UTF-8',
date: 'Thu, 22 Sep 2016 09:22:31 GMT',
expires: 'Thu, 22 Sep 2016 09:22:31 GMT',
'cache-control': 'private, max-age=0',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '1; mode=block',
server: 'GSE',
'alt-svc': 'quic=":443"; ma=2592000; v="36,35,34,33,32"',
'accept-ranges': 'none',
vary: 'Accept-Encoding',
connection: 'close' },
body: '<HTML>\n<HEAD>\n<TITLE>UnauthorizedRegistration</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>UnauthorizedRegistration</H1>\n<H2>Error 400</H2>\n</BODY>\n</HTML>\n' }
Please let me know if anyone came across this issue.
Related
How can I download a file using the POST method along with some headers and data (of the type: "content-type: application/x-www-form-urlencoded") in React Native?
When I send a request to the URL, the following is returned in the Response Header:
content-disposition: attachment; filename="PAPR_Pginas_Web_2.pdf"
content-type: application/pdf
date: Sun, 07 Aug 2022 13:59:00 GMT
last-modified: Thu, 01 Jan 1970 00:00:00 GMT
server: Apache
strict-transport-security: max-age=86400
x-powered-by: JSF/1.2
x-xss-protection: 1; mode=block
I'm using this code:
const donwloadPDF = async (uri) => {
const downloadInstance = FileSystem.createDownloadResumable(uri, FileSystem.documentDirectory + "file.pdf");
const result = await downloadInstance.downloadAsync();
if (result.status === 200) {
Sharing.shareAsync(result.uri, { dialogTitle: "Share or Save" });
} else {
console.log("Failed to Download");
}
};
const getFile = async (payload) => {
try {
const response = await fetch(URL, {
method: "POST",
headers: headers2,
body: formBody(payload),
});
const content = await response.json();
donwloadPDF(content); // Some URI
} catch (error) {
console.error(error);
}
};
But is returned the error: JSON Parse error: Unrecognized token '%'
I'm actually trying to download a zip file from a Gitlab REST endpoint that is supposed to return the the repository for a given projectID.
I used axios to call the endpoint and tried to directly upload the response data to S3, but it seems to be returning a corrupt file as the zip that it returns says it cannot be opened.
I am doing the downloading of this file in a serverless function and attempting to return an S3 URL to the client.
Headers for the response
res.headers {
date: 'Wed, 19 Jan 2022 13:44:42 GMT',
'content-type': 'application/zip',
'transfer-encoding': 'chunked',
connection: 'close',
'cache-control': 'max-age=0, private, must-revalidate',
'content-disposition': 'attachment; filename="third-project-eac3ea41c782df4bee4fe07ecc3bf356f7f74f47-eac3ea41c782df4bee4fe07ecc3bf356f7f74f47.zip"',
'content-transfer-encoding': 'binary',
etag: 'W/"12ae32cb1ec02d01eda3581b127c1fee"',
vary: 'Origin',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-request-id': '01FSS9A6W1RM77TYMFM6G7HKZ8',
'x-runtime': '0.063985',
'strict-transport-security': 'max-age=31536000',
'referrer-policy': 'strict-origin-when-cross-origin',
'ratelimit-observed': '2',
'ratelimit-remaining': '1998',
'ratelimit-reset': '1642599941',
'ratelimit-resettime': 'Wed, 19 Jan 2022 13:45:41 GMT',
'ratelimit-limit': '2000',
'gitlab-lb': 'fe-17-lb-gprd',
'gitlab-sv': 'localhost',
'cf-cache-status': 'MISS',
'expect-ct': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
'report-to': '{"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=r6XcPGaiU7JhlicrSC9iBZgXXCOMoBMXjU8kvxjZGb5UkUQBIjemmAOOX39m1ijVCnQROVhNNxc6B%2B4x%2FNf5ZG9cc8GLY%2BfMYUE29gJkHN624QKJRSX8HBrMqEQ%3D"}],"group":"cf-nel","max_age":604800}',
nel: '{"success_fraction":0.01,"report_to":"cf-nel","max_age":604800}',
server: 'cloudflare',
'cf-ray': '6d007fcb7a8a8e63-PDX'
}
This it the code I'm using
const requestURL = `https://gitlab.com/api/v4/projects/${repoID}/repository/archive.zip?sha=${commitSHA}`;
let url = await Axios({
method: "GET",
url: requestURL,
headers: {
Accept: "*/*",
Authorization: "Bearer " + authToken,
},
})
.then(async (res) => {
const Key = "path/to/file";
const params = {
Bucket: BUCKET_URL,
Key,
Body: res.data,
ContentType: "application/zip",
};
await s3.upload(params).promise();
const URL = await s3.getSignedUrl("getObject", {
Bucket: BUCKET_URL,
Key,
ResponseContentDisposition:'attachment; filename = test.zip"',
});
return URL ;
})
.catch((error) => {
console.log(error);
});
return url;
But when I try and access this URL on my browser from the frontend, It returns a file test.zip which is larger and corrupt.
This is a screenshot of the data that I received on postman,
if I click save response and name the file filename.zip it shows the actual contents of the file.
Any help would be appreciated!
This worked!
const requestURL = `https://gitlab.com/api/v4/projects/${repoID}/repository/archive.zip?sha=${commitSHA}`;
let url = await Axios.get(requestURL,{
headers: {
Accept: "*/*",
Authorization: "Bearer " + authToken,
},
responseType:'arraybuffer'
})
.then(async (res) => {
const bufferData = Buffer.from(res.data)
const Key = "path/to/file";
const params = {
Bucket: BUCKET_URL,
Key,
Body: bufferData,
ContentType: "buffer",
};
await s3.upload(params).promise();
const URL = await s3.getSignedUrl("getObject", {
Bucket: BUCKET_URL,
Key,
ResponseContentDisposition:'attachment; filename = test.zip"',
});
return URL ;
})
.catch((error) => {
console.log(error);
});
return url;
Postman output:
HTTP/1.0 200 OK
Cache-Control: no-cache, private
Content-Type: application/json
Date: Fri, 08 Feb 2019 12:13:36 GMT
{"status":1,"msg":"success","celeb":[{"id":1,"name":"Test Name"....
I'm getting my json in postman like this.
when I try to use fetch(), I'm getting an error json parse error, unknown identifier HTTP
fetch('https://myurl/fetch')
.then((response) => response.json())
.then((response) => {...}
let func = async () => {
const url = 'https://myurl/fetch';
const data = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
token: await AsyncStorage.getItem(ACCESS_TOKEN), /*or whatever you have on your api*/
}),
};
const response = await fetch(url , data);
const responseData = await response.json();
console.log(responseData);
}
I believe you are missing to set to configure you API call method, headers, mode etc... Check out Fetch Examples for a better explanation.
I am trying to make Express session work with Next.js, and have successfully done so on the client side, but I am having trouble with API calls made from inside getInitialProps.
Note: I am using isomorphic-unfetch to make API calls. My Next.js installation runs on localhost:3000, my Express server on localhost:5000.
Here is an example of a client side API call (outside of getInitialProps):
componentDidMount() {
fetch('/path/to/endpoint', {
method: 'GET',
credentials: 'include',
}).then((res) => console.log(res));
}
I'm logging res here because I wanted to see the headers. Turns out this request has an empty headers object. If i resolve the promise I get the data I requested though. The session ID from this call stays consistent on the server even if I refresh the page. Everything is working as expected here.
Here is an example of an API call inside getInitialProps:
static async getInitialProps(ctx) {
fetch('/path/to/endpoint', {
method: 'GET',
credentials: 'include',
}).then((res) => console.log(res.headers));
}
Again, logging to see the headers. This response has headers, they look like this:
Headers {
_headers:
{ 'x-powered-by': [ 'Express' ],
'access-control-allow-origin': [ 'http://localhost:3000' ],
vary: [ 'Origin, Accept-Encoding' ],
'access-control-allow-credentials': [ 'true' ],
'x-frame-options': [ 'SAMEORIGIN' ],
'x-xss-protection': [ '1; mode=block' ],
'set-cookie'['YgJGcZPBgbE_nEqqLZpw0ba0pyaf2eNS','connect.sid=s%3AYgJGcZPBgbE_nEqqLZpw0ba0pyaf2eNS.Oye%2F7%2BsyXrrLJwphEJ3nq3yMkBhM3%2Fm4PCl9KIV%2FTzA; Path=/; Expires=Sun, 05 Aug 2018 15:56:52 GMT; HttpOnly' ],
'content-type': [ 'application/json; charset=utf-8' ],
'content-length': [ '246' ],
etag: [ 'W/"f6-82FKQ+ERtkxLiKa8hEIeY4kgGgE"' ],
date: [ 'Sun, 22 Jul 2018 15:56:52 GMT' ],
connection: [ 'close' ] } }
As you can see there is connect.sid (express session ID) in my set-cookie header, but the problem is that the connect.sid cookie changes whenever I refresh the page and does not match the session ID of client side API calls (which stays the same even after refreshing the page).
My session object on the Express server looks like this:
app.use(
session({
resave: false,
name: 'connect.sid',
saveUninitialized: false,
secret: SESSION_SECRET,
unset: 'destroy',
cookie: {
maxAge: 3600000 * 24 * 14,
secure: false,
},
store: new MongoStore({
url: mongoUrl,
autoReconnect: true,
}),
})
);
If anyone has an idea how I can make API calls from inside getInitialProps work with express session I'd appreciate the input! Thank you in advance.
I found the solution. Instead of using credentials: 'include' I had to send the session cookie in the request header. Here's a working request inside getInitialProps.
static async getInitialProps(ctx) {
const res = await fetch('path/to/endpoint', {
headers: {
cookie: ctx.req.headers.cookie,
},
});
const user = await res.json();
return { user };
}
I am using fetch method to make API calls on the server and noted it is making multiple requests at the same time and due to this it increases 30% RPM on the server
Can someone please help in preventing multiple calls and understanding why is it happening?
Below you can see React Native code and server logs
React Native Code
fetch(url, {
method: "GET",
headers: {
'Accept': "application/json",
'Content-Type': "application/json"
}
}).then((resp) => {
if (resp.status === 200) {
resp.text().then(function(data) {
var resData = JSON.parse(data);
}
}
}
Server Logs
[Wed Jan 25 12:14:08.323939 2017] [:error] [pid 13832] 2017-01-25 12:14:08.323658 URL: /driver/upcoming-bookings/ User: {'id': '', 'email': 'Anonymous'} HTTP Method: GET Params: {u'imei': u'359375062977098'}
[Wed Jan 25 12:14:08.631057 2017] [:error] [pid 14306] 2017-01-25 12:14:08.630777 URL: /driver/upcoming-bookings/ User: {'id': '', 'email': 'Anonymous'} HTTP Method: GET Params: {u'imei': u'359375062977098'}
[Wed Jan 25 12:14:09.103341 2017] [:error] [pid 14307] 2017-01-25 12:14:09.102915 URL: /driver/upcoming-bookings/ User: {'id': '', 'email': 'Anonymous'} HTTP Method: GET Params: {u'imei': u'359375062977098'}