Fetch request headers vs. Postman headers - firefox

Using Postman I'm able to do the following call:
GET https://tickets.ramdom.com/api/events/95
Request Headers
Host: tickets.ramdom.com
Cookie: OptanonConsent=isIABGlobal=false
Cache-Control: no-cache
Postman-Token: db42ad48-62f1-4e3f-8903-66002116e8a3
The call works fine. Now I want to reproduce the same call using fetch and Firefox console.
So I create the following piece of code:
const opts = {
headers: {
Host: 'tickets.ramdom.com',
Cookie: 'OptanonConsent=isIABGlobal=false'
}
};
fetch('hhttps://tickets.ramdom.com/api/events/95', opts)
.then((response) => {
alert(response)
})
.catch((error) => {
alert(error)
});
But I always get the following error:
TypeError: NetworkError when attempting to fetch resource.
Do you know what I'm doing wrong?
Thanks

Related

How to override cy.request() and set up bearer authorization header globally?

I need to set the authorization bearer header for cy.request() globally to avoid setting it up multiple times.
Here I found some potential way to do it.
So in my support/commands.ts I have:
Cypress.Commands.overwrite('request', (originalFn, ...options) => {
const optionsObject = options[0];
if (optionsObject === Object(optionsObject)) {
optionsObject.headers = {
authorization: `Bearer ${Cypress.env('authorizationToken')}`,
...optionsObject.headers,
};
return originalFn(optionsObject);
}
return originalFn(...options);
});
And in the test I have:
cy.request({
method: 'POST',
url: '/someEndpoint',
body: someBody
}).then(response => {
expect(response.status).eq(200);
return response.body;
});
And unfortunately, I get 401: Unauthorized error and it looks like the authorization bearer token was not added to headers:
What do I do wrong here? I use Cypress v 10.10.0

Getting error when returning list from rest service admin-on-rest

I'm getting the following error on my first admin component.
uncaught at handleFetch TypeError: newRecords.reduce is not a function
When I attempt to query my rest-api. I'm using the majority of the supplied simple rest client with some additional security headers thrown in.
My response from my API is:
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Content-Range: Account 0-0/1
Server: Kestrel
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Content-Range
Request-Context: appId=cid-v1:9f32da6c-a0dd-445f-b59f-d5d01ee6c462
X-AA-Request-ID: ad76be2b-0a29-4179-8fab-6ac0b83e411b
X-SourceFiles: =?UTF-8?B?RTpcRGV2XEFBSHViXEFBLkh1Yi5TZXR0aW5ncy5TZXJ2aWNlXEFBLkh1Yi5TZXR0aW5ncy5TZXJ2aWNlXGFwaVx2MVxhY2NvdW50?=
X-Powered-By: ASP.NET
Date: Tue, 15 Aug 2017 02:56:56 GMT
The body of the response has:
{"data":[{"changeManagements":[],"serviceProfiles":[],"id":1,"login":"cuken","permissionLevel":9001,"note":"This is a dev test user"}],"totalItems":1}
EDIT
Here is the fetch.js file I modified from the simple rest client example:
import HttpError from './HttpError';
export const fetchJson = (url, options = {}) => {
const requestHeaders = options.headers || new Headers({
Accept: 'application/json',
'X-AA-ClientName': 'fc5f3712-64fc-4ca4-9e5f-d4b6edeb46d4',
'X-AA-ApiKey': '80b4ccbf-a741-42ad-aacc-50c4309de8e6',
});
if (!(options && options.body && options.body instanceof FormData)) {
requestHeaders.set('Content-Type', 'application/json');
}
if (options.user && options.user.authenticated && options.user.token) {
requestHeaders.set('Authorization', options.user.token);
}
return fetch(url, { ...options, headers: requestHeaders })
.then(response => response.text().then(text => ({
status: response.status,
statusText: response.statusText,
headers: response.headers,
body: text,
})))
.then(({ status, statusText, headers, body }) => {
let json;
try {
json = JSON.parse(body);
} catch (e) {
// not json, no big deal
}
if (status < 200 || status >= 300) {
return Promise.reject(new HttpError((json && json.message) || statusText, status));
}
return { status, headers, body, json };
});
};
export const queryParameters = data => Object.keys(data)
.map(key => [key, data[key]].map(encodeURIComponent).join('='))
.join('&');
The simple.js file is an exact copy from the repo.
What did I do wrong?
You need a dedicated auth client to handle the auth types and shoot the appropriate actions
https://marmelab.com/admin-on-rest/Admin.html#authclient
That's because your API response is not what the simpleRestClient expects:
It should only contains
[{"changeManagements":[],"serviceProfiles":[],"id":1,"login":"cuken","permissionLevel":9001,"note":"This is a dev test user"}]
No data nor totalItems keys. As stated in the documentation:
The simple REST client expects the API to include a Content-Range header in the response to GET_LIST calls. The value must be the total number of resources in the collection. This allows admin-on-rest to know how many pages of resources there are in total, and build the pagination controls.

CORS Issue When Requesting from ExtJS to node.js. Request or Response Header Incorrect?

I am having issues with making an ExtJS AJAX request to the Nodejs server between two different domains within our network and will appreciate any help. Response fails when attempting from both http and https from ExtJS client side but a Curl from my local via http returns 200 OK with proper data. We are working with content type application/json.
ExtJS onReady function has enabled CORS:
Ext.onReady(function () {
Ext.Ajax.cors = true;
Ext.Ajax.useDefaultXhrHeader = false;
... (code removed)
})
A test from my ExtJS client side on a known working URL that will properly create the ExtJS datastore (brings back 200 OK):
Ext.create('Ext.data.Store', {
id : 'countryStore',
model : 'country',
autoLoad : true,
autoDestroy: true,
proxy: {
type: 'rest',
url : 'https://restcountries.eu/rest/v1/all',
},
reader: {
type : 'json',
headers: {'Accept': 'application/json'},
totalProperty : 'total',
successProperty: 'success',
messageProperty: 'message'
}
});
However, when attempting a request to our Nodejs server via
http:
Ext.create('Ext.data.Store', {
id : 'circuits',
model : 'circuit',
autoLoad : true,
autoDestroy: true,
proxy: {
type: 'rest',
url : 'http://ourNodeJsServerDomain:5500/v3/circuits',
},
reader: {
type : 'json',
headers: {'Accept': 'application/json'},
totalProperty : 'total',
successProperty: 'success',
messageProperty: 'message'
}
});
returns the following in Chrome's console:
Mixed Content: The page at 'https://ourExtJsDevClientSide' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://ourNodeJsServerDomain:5500/v3/circuits?_dc=1430149427032&page=1&start=0&limit=50'. This request has been blocked; the content must be served over HTTPS.
Now, when attempted over https:
Firefox shows:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ourNodeJsServerDomain:5500/v3/circuits?_dc=1430151516741&page=1&start=0&limit=50. This can be fixed by moving the resource to the same domain or enabling CORS.
and the Request Header doesn't show "application/json", is this an issue?:
Accept
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding
gzip, deflate
Accept-Language
en-US,en;q=0.5
Host
ourNodeJsServerDomain:5500
Origin
https://ourExtJsDevClientSide
Referer
https://ourExtJsDevClientSide
User-Agent
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:37.0) Gecko/20100101 Firefox/37.0
I then tried with Curl to see what the responses were to help debug
on http gives a 200 OK response but Access-Control-Allow-Origin is undefined even when we are defining it as "*":
curl http://ourNodeJsServerDomain:5500/v3circuits?_limit=1 -v
> GET /v3/circuits?_limit=1 HTTP/1.1
> User-Agent: curl/7.37.1
> Host: ourNodeJsServerDomain:5500
> Accept: */*
>
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Access-Control-Allow-Origin: undefined
< Access-Control-Allow-Methods: GET
< Access-Control-Allow-Headers: Content-Type
< Content-Type: application/json; charset=utf-8
< Content-Length: 1126
< ETag: W/"MlbRIlFPCV6w7+PmPoVYiA=="
< Date: Mon, 27 Apr 2015 16:24:18 GMT
< Connection: keep-alive
<
[
{ *good json data returned here* } ]
then when I attempt to Curl via https
curl https://ourNodeJsServerDomain:5500/v3/circuits?_limit=1 -v
* Server aborted the SSL handshake
* Closing connection 0
curl: (35) Server aborted the SSL handshake
We have enabled CORS on our Nodejs server:
router
.all('*', function(req, res, next){
res.setHeader('Content-Type', 'application/json');
// res.setHeader("Access-Control-Allow-Origin", req.headers.origin);
// console.log('\n\nreq.headers.origin ===================== ' + req.headers.origin);
//I have tried allowing all * via res.SetHeader and res.header and neither is defining the Access-Control-Allow-Origin properly when curling
//res.setHeader("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Methods', 'GET');
res.header('Access-Control-Allow-Headers', 'Content-Type');
I have attempted to be detailed in my thought process and I am willing to try new ways to determine how to understand and solve this.
* SOLUTION *
The issue is mixed content from the browser. Our client UI is on https (secure) whereas we were requesting http (unsecure) content from the nodejs server. We needed to allow for our nodejs server to run on https
We generated SSL certifications and implemented them onto our nodejs server.
Within the nodejs code, we enabled CORS with the CORS module and are running both http and https servers:
// enable CORS for all requests
var cors = require('cors');
app.use(cors());
// for certifications
var credentials = {
key: fs.readFileSync('our.key'),
cert: fs.readFileSync('our.crt')
};
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
httpServer.listen(port, function() {
console.log('HTTP server listening on port ' + port);
});
httpsServer.listen(httpsPort, function() {
console.log('HTTPS server listening on port ' + httpsPort);
});
There seems to be issues with both CORS and HTTPS in your server... You should try this middleware for the CORS part, and make it work when accessing the page in raw HTTP first. As far as I know, you'll have to use different ports for HTTP and HTTPS. And you will also probably need to enable CORS credentials. As I said, I think you'd better make it work in HTTP first ;)
Then, on the Ext part, as already mentioned in comments, you should probably disable default headers (or you'll have to make all of them accepted by your server; see the first comment to this answer). But you need to do that on the proxy, because apparently it replaces the global setting in Ext.Ajax.
So, something like this:
Ext.create('Ext.data.Store', {
id : 'countryStore',
model : 'country',
autoLoad : true,
autoDestroy: true,
proxy: {
type: 'rest',
url : 'https://restcountries.eu/rest/v1/all',
useDefaultXhrHeader: false, // <= HERE
reader: {
type : 'json',
headers: {'Accept': 'application/json'},
totalProperty : 'total',
successProperty: 'success',
messageProperty: 'message'
}
} // <= and notice this change
});
Probably unrelated, but note that your indendation was incorrect and hid the fact that the reader option was applied to the store itself instead of the proxy (so it was ignored).

Http multipart request using Google Drive API

I am trying to send HTTP multipart request using Google Drive API to insert file in Google Drive.
I am following the link below : Multipart upload
However, I am getting a Bad request error.
Below is the request string which I have created using the documentation link above:
String content = '\r\n--' + boundary + '\r\n';
content +='Content-Type: '+'application/json; charset=UTF-8'+'\r\n\r\n';
content +='{' + '\r\n';
content +='"title": "My File"'+'\r\n';
content +='}'+'\r\n\r\n';
content += '--'+boundary + '\r\n';
content +='Content-Type: '+'text/plain'+'\r\n';
content += EncodingUtil.base64Encode(b)+'\r\n';
content += '-'+boundary+'-\r\n';
Please can someone tell me what I am missing here ??
I was having trouble with this as well,
but if you look at the code for the google drive API on github:
Github Drive API
The request parameters accept a media object, which can have a body and mimeType.
I was working with a service account, and this lets you upload files directly to drive.
auth.getApplicationDefault(function(err, authClient) {
if (err) {
console.log('Authentication failed because of ', err);
return;
}
if (authClient.createScopedRequired && authClient.createScopedRequired()) {
var scopes = ['https://www.googleapis.com/auth/drive'];
authClient = authClient.createScoped(scopes);
}
var request = {
project: "YOUR_PROJECT",
auth: authClient,
resource: {
parents: ['blah']
},
media: {
body: 'hi',
mimeType: 'text/plain'
}
};
drive.files.create(request, function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
});
});
I had this problem too and after trying some changes I finally reached a working example:
Header :
POST /upload/drive/v2/files?uploadType=multipart&access_token=ya29.CjAmA2j6eonCiROaNum-V1cWdFVH2vXpNiXAsXK6iLPu7K54tD4uNsmH-eEycMcnaBE HTTP/1.1
Host: www.googleapis.com
Accept: */*
Content-Type: multipart/related; boundary="foo_bar_baz"
Content-Length: 150
remember to add boundary="foo_bar_baz" in Content-Type field
Body :
--foo_bar_baz
Content-Type: application/json; charset=UTF-8
{
"title": "My File"
}
--foo_bar_baz
Content-Type: text/txt
JPEG data
--foo_bar_baz--

Ajax file upload in node.js

Want to upload a file using ajax for this using this uploader
http://valums.com/ajax-upload/
and in node.js write this code which is working with normal file upload without ajax .
console.log("request " + sys.inspect(req.headers));
req.on('data', function(chunk) {
console.log("Received body data:");
// console.log(chunk.toString());
});
var form = new formidable.IncomingForm();
form.parse(req, function(err,fields, files) {
console.log('in if condition'+sys.inspect({fields: fields, files: files}));
fs.writeFile("upload/"+files.upload.name, files.upload,'utf8', function (err) {
if (err) throw err;
console.log('It\'s saved!');
client.putFile("upload/"+files.upload.name, files.upload.name, function(err, res){
if (err) throw err;
if (200 == res.statusCode) {
console.log('saved to s3');
httpres.writeHead(200, {'content-type': 'text/plain'});
httpres.write('received 1upload:\n\n');
httpres.end();
}
});
});
});
But this is giving error ?
request { host: 'myhost:8001',
'user-agent': 'Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'accept-language': 'en-us,en;q=0.5',
'accept-encoding': 'gzip, deflate',
'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'keep-alive': '115',
connection: 'keep-alive',
origin: 'http://myhost',
'access-control-request-method': 'POST',
'access-control-request-headers': 'content-type' }
events.js:45
throw arguments[1]; // Unhandled 'error' event
^
Error: bad content-type header, no content-type
at IncomingForm._parseContentType (/usr/local/lib/node/.npm/formidable/1.0.0/package/lib/formidable/incoming_form.js:196:17)
at IncomingForm.writeHeaders (/usr/local/lib/node/.npm/formidable/1.0.0/package/lib/formidable/incoming_form.js:109:8)
at IncomingForm.parse (/usr/local/lib/node/.npm/formidable/1.0.0/package/lib/formidable/incoming_form.js:65:8)
at Server.<anonymous> (/home/myfolder/myfolder/newcontentserver.js:29:18)
at Server.emit (events.js:67:17)
at HTTPParser.onIncoming (http.js:1108:12)
at HTTPParser.onHeadersComplete (http.js:108:31)
at Socket.ondata (http.js:1007:22)
at Socket._onReadable (net.js:678:27)
at IOWatcher.onReadable [as callback] (net.js:177:10)
I think problem is the content-type is not set in the headers By ajax file upload .thats why this error is coming how can i set the header in this uploader , or how can i make a file in node.js server by incoming data.
As it is using the xhr so i think i can't use the formidable.incomingform() what should i use?
Looking at the latest fileuploader.js source code on github he does set the content type
xhr.setRequestHeader("Content-Type", "application/octet-stream");
I believe your problem is elsewhere.

Resources