Beginner question, I am using the fetch API in one of my Cloudflare Service Worker to send request to a third party; Everything works fine that I am able to send out the request and receive response; But now I have a need to log everything I sent and received, which I am not sure how exactly can I do so;
The main requirement:
Able to log the whole request header being sent
The problem is that the request header that I specified is not the full header being sent, like in the following example I only specified the content-type, but in real practice it will send with more properties added by the application itself, e.g. accept, x-forwarded-for, content-length, etc.
Request:
var toThirdPartyReqMethod = 'POST';
var toThirdPartyReqHeader = {'content-type': 'application/json'};
var toThirdPartyReqSetting = {
method: toThirdPartyReqMethod,
headers: toThirdPartyReqHeader,
body: toThirdPartyReqBodyArrayBuffer
};
var toThirdPartyUrl = "https://somewhere.com";
var fromThirdPartyResponse = await fetch(toThirdPartyUrl, toThirdPartyReqSetting)
var fromThirdPartyResponseBodyArrayBuffer = await fromThirdPartyResponse.arrayBuffer();
I am able to use fromThirdPartyResponse to digest the response; but I have no idea how to record the exact request I sent out.
I tried to do it as follows:
var oriReqHeaderContentType = fromThirdPartyResponse.request.headers.get("content-type");
But obviously it is not the right answer and returned with the following error:
TypeError: Cannot read property 'headers' of undefined
Anyone gets some idea of how to log the request being sent when using fetch API?
Sorry for asking beginner questions :(
You can access request headers like this
const contentType = req.get("Content-Type");
Related
I am trying to send the token in the headers of an HTTP request from backend to the frontend along with sending my own defined string. However, I am getting an issue. The token is being printed as null on the client-side. I don't know why:
Here's my code:
Node/Express
if (bcrypt.compareSync(passcode, results[0].password))
{
const token = jwt.sign({id: email}, secret, {expiresIn: 86400 });
console.log(token);
if(results[0].userrights == 'full')
{
res.setHeader('x-access-token', token);
res.send("Full Authorization");
}
//rest of the code
}
Angular
this.http.post('http://localhost:3000/api/login', form.value, {responseType: "text", observe:
'response'})
.subscribe(responseData => {
console.log(responseData);
console.log(responseData.headers.get('x-access-token')); //prints null on the console
I have searched quite a bit and found different examples which is making it very confusing. I don't want to use response status rather my own defined string. I have tried different things to print the variable but it still is throwing as null.
If you are using a browser extension to allow CORS requests then Access-Control-Expose-Headers should be added to the headers on server side. Please try adding the following line: res.setHeader('Access-Control-Expose-Headers', '*')
Angular2 's Http.post is not returning headers in the response of a POST method invocation
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
[I am trying to send parameter with GET request on RESTLET Netsuite !!
but i am continuously facing issue 403 forbidden when i am trying to concatenate parameter with URL , without parameter Request is working good and getting response but i want to send parameter so now i am trying to send parameter through Header but not able to read on server side !! please help me out .how to read request header values/parameters on Netsuite RESTLET.
1-first i tried concatenate with +"&name=asd" and then Uri builder throws error 403 forbidden
2-Now i am sending parameters through request.header.add("name":"asd") working good
This is my client side request code in which i am attaching parameters in request header
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.ContentType = "application/json";
request.Method = "GET";
request.Headers.Add(header);
request.Headers.Add("email", "polutry#key-stone.co");
request.Headers.Add("password", "123-4567");
WebResponse response = request.GetResponse();///here i got 403 on concatination ////
function getCustomer(context)
{
var request =https.request.headers;///headers function not defined
// var email =request.email;
//var password = request.password;
}
Want to get header values on server side][1]
[1]: https://i.stack.imgur.com/SEB68.png
In RESTlet you don't have access to request-headers, instead you get all the arguments passed to RESTlet in scriptContext(function argument to RESTlet entry point, get in current case).
Check this out on how to use RESTlet and how you can pass arguments.
Note: Add { "Content-Type": "application/json" } header since you want to pass data to RESTlet.
I want to send multiple files to Github repository via nodejs. Tried several approaches and end up using node-rest-client module. Tried below code send a sample file to repository called 'metadata'. But after post I am getting error message "Request forbidden by administrative rules. Please make sure your request has a User-Agent header"...please let me know if anyone faced this error before and get rid of it.
convertval = "somedata";
var dataObj = {
"message": "my commit message",
"committer": {
"name": "Scott Chacon",
"email": "ravindra.devagiri#gmail.com"
},
"content": "bXkgbmV3IGZpbGUgY29udGVudHM="
}
debugger;
var Client = require('node-rest-client').Client;
var client = new Client()
var args = {
data: dataObj,
headers: { 'Content-Type': 'application/json' },
};
client.post("https://api.github.com/repos/metadata/contents", args, function (data, response) {
console.log("file send: True : " + data);
});
According to the REST API:
All API requests MUST include a valid User-Agent header. Requests with
no User-Agent header will be rejected.
First of all, you need to define 'User-Agent' with value 'request' in your request header. Refer to this link.
Second, endpoint you are trying to call might require authentication. Generate a personal token from here, add that token in your request header, 'Authorization': 'token '.
If you're using Git extensively in your code, I suggest you to use this - Nodegit.
Edit:
I don't think sending multiple files in a single request is possible in 'Contents' endpoints group (link).
You can checkout Git Data API (as discussed here).
My code is as follows
var http = require('http');
var host=...
var postData=({
//some fun stuff
})
var postOptions ={
host: host,
path: '/api/dostuff',
method: 'POST',
headers:{
AppID:"some stuff",
Authorization: "OAuth token",
"Content-Type":"application/json"
},
};
var req = http.request(postOptions, function(res){
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
//sanitize data stuff here
console.log("DATA HERE: "+ data);
return data;
});
});
req.write(JSON.stringify(postData));
req.end();
It's a basic HTTP post to a C# server. The important stuff is in the headers. I send the app ID (which is ~50 characters) and the OAuth token (which can be thousands of characters). Right now, the server isn't set up to do anything with the Authorization header. It doesn't even check if its there.
My problem is that when I populate the Authorization header (or any header) with a few random characters as a test, the post succeeds. When I tried it again with a full valid Authorization token (which, to reiterate, is very long) it fails. No matter which part of the header i fill, once it gets too full it returns an error. The error I receive is "Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details". I was somewhat certain this is a server issue, but when I tried running the exact same body and headers in Postman, I got a valid response.
Does anyone have any idea what is causing this?
There's a compiled constant that's defined to be 80k for Node HTTP headers. Are you running into that? I'd recommend seeing how big the header is with your OAuth token. It shouldn't exceed 80k though, and FWIW, even a kilobyte is huge for OAuth... But regardless... Try dumping the size of the headers (in bytes).
I crate a mobile service and also a custom api for that in Azure. I use fiddler to send request and do some basic and simple testing.
At Azure side, I create a custom api for my mobile service. Let say the name is ExampleCustomApi. And in the code I have
exports.put = function(request, response) {
var tags = request.parameters.tags;
...
...
}
At fiddler side, I set http method to "PUT" and the url to my custom api.
Then I set a request body to { "tags": "tag1" }.
When I execute the request in fiddler, I receive 500 back. The log in Azure's mobile service says that parameters is undefined.
My question, then, is how to get the request body at the server side. I look at the document of request object, it seems to me that parameters is the one I should use, but it doesn't work.
request is an object in express.js library.
This is the documentation from MSDN http://msdn.microsoft.com/library/azure/jj554218.aspx
the documentation from express.js http://expressjs.com/api.html#req.body
And I can use request.body to get the body content.
After many attempts we cracked getting the content from a weburl. Hope this helps :) Jsonbody would hold your page content. This is a copy where we pulled json from one of our API's
var message = "try";
var jsonBody = "";
var request = require('request');
request.get({
url: "https://superduperwebaddress.com/api/pull"},
function(error,response,body){
if(!error)
{
var mybody = JSON.parse(body);
jsonBody = mybody;
console.warn("we are here well");
}else{
console.error(error);
}
}
);