Can't 'save' incomming cookie's from my go server - javascript

I made a go server that can do the basics. Now I want to do a request to my server from my node.js frontend (Axios) get a cookie back (for my login system) here is the code for putting the cookie in my response:
var hashKey = []byte("testkey") //for testing purpopes
var blockKey = []byte(securecookie.GenerateRandomKey(32))
var s = securecookie.New(hashKey, blockKey)
if encoded, err := s.Encode("cookie-name", value); err == nil {
cookie := &http.Cookie{
Name: "cookie-name",
Value: encoded,
Path: "/",
Secure: true,
HttpOnly: true,
}
http.SetCookie(*w, cookie) // w = *http.ResponseWriter
...
when I use my REST tool to see what I get I can see that the 'set-cookie' header is present. The same is If I inspect in Microsoft Edge I can see the set-cookie header. But if I inspect in Google Chrome then I can't see the header. Also if I look in the cookies tab in both Chrome and edge the cookie is not set.
this is my function that is ran for the request:
async post( url, data, ct ) {
try {
const res = await axios.post(url, data, {
headers: {
'Content-Type': (ct || "text/plain")
},
withCredentials: true
});
if (res.status === 200) {
return res.data;
}
} catch (e) {
console.error(e);
return false;
}
}
my Response Headers:
server: nginx/1.14.0 (Ubuntu)
date: Thu, 17 Jan 2019 14:29:07 GMT
content-type: text/plain charset=utf-8
content-length: 4
connection: keep-alive
setcookie:cookiename=MTU0NzczNTM0N3xGOTJYUUw5TFNXZHI2dU9jT3hCeTZUTE5TaTBFNU1XN1F 5WGMzb3c1dGZRUENEU2xPZHFwTXJQLW8zND18_VCYxNVRbIAUrs9_8EcGpTUEiqVyYL_2M5Olbjhnkeg =; Path=/
access-control-allow-origin:https://beta.bvwitteveen.nl
access-control-allow-methods:GET, POST, OPTIONS
access-control-allow-credentials:true
access-control-allow-headers:DNT,User-Agent,X-Requested-With,If-
ModifiedSince,Cache-Control,Content-Type,Range,Set-Cookie
access-control-expose-headers:Content-Length,Content-Range
Why is my cookie behaving so weird? What am I doing wrong here?

Related

typeerror: cannot read property of undefined javascript - empty JSON object from fetch despite postman showing object from API

My react app is supposed to attain a JSON object to display information onto dashboard. There is an object when I check postman using the URL which is what I want to use however when trying to access the fields from the object I am getting a type error of undefined javascript. Even when I console log the object it is an empty array.
The below is the fetch request which has worked for all other aspects of the application but not for this part of it.
API call in Postman using the same URL gives the following response:
[
{
"average_hb": "85.27",
"average_os": "92.84",
"max_hb": "86.35",
"max_os": "96.54"
}
]
get/ call response on chrome developer tools:
Request URL: http://127.0.0.1:8000/dashboard/utilisation/T/detail/get/
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:8000
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Origin: http://localhost:3000
Allow: GET, HEAD, OPTIONS
Content-Length: 79
Content-Type: application/json
Date: Tue, 07 Sep 2021 21:07:37 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.7.7
Vary: Accept, Origin, Cookie
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
The outcome I would like from this is to be able to display the values of the four variables (average_hb etc.) onto application. These fields come from Django back end which as mentioned, does return an object when looking in postman.
function UtilisationDetail(props){
var average_hb = 0;
var average_os = 0;
var max_hb = 0;
var max_os = 0;
const [utilisations, setUtilisation] = useState([]);
useEffect(()=>{
fetch(`http://127.0.0.1:8000/dashboard/utilisation/${props.warehouseState}/detail/get/`, {
method:'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then( resp => resp.json())
.then(resp => setUtilisation(resp))
// .catch( error => console.log(error) )
}, [props.warehouseState])
function setDetails(){
try{
console.log(utilisations)
average_hb = utilisations[0].average_hb;
average_os = utilisations[0].average_os;
max_hb = utilisations[0].max_hb;
max_os = utilisations[0].max_os;
}
catch(e){
}
}
return(
<div>
{setDetails}
<h4>Space</h4>
<p>Average HB {average_hb}</p>
<p>Average OS {average_os}</p>
<p>Max HB {max_hb}</p>
<p>Max OS {max_os}</p>
</div>
)
}
export default UtilisationDetail;
You need to use another useEffect for setDetails() that is dependent on utilisations, and have a guard against the utilisations.length
useEffect(() => {
if(utilisations.length) setDetails()
}, [utilisations])
And then handle your return statement differently to render the output.

Reading response body beyond content-length

I'm working against an HTTP server that sometimes returns a body that is longer than the response's Content-length header. For example, curl shows me this:
curl -v -k -H "Cookie: VerySecretCookie" https://fqdn/path
[...]
< HTTP/1.1 200 200
< Date: Thu, 01 Jul 2021 10:45:32 GMT
[...]
< X-Frame-Options: SAMEORIGIN
<
* Excess found in a non pipelined read: excess = 83, size = 2021, maxdownload = 2021, bytecount = 0
I'm trying to issue a similar request via axios and read the entire body, even beyond the Content-length. However, it seems to stop after Content-length bytes have been read.
This is the config I'm using:
const config: AxiosRequestConfig = {
method: 'GET',
responseType: 'stream',
maxRedirects: 0,
decompress: false,
timeout: 60000,
};
And I then retrieve the response via:
private async streamToString(stream: Stream): Promise<string> {
return new Promise((res, rej) => {
let data = '';
stream.on('end', () => {
res(data);
});
stream.on('error', (err) => {
rej(err);
});
stream.on('data', (chunk) => {
data += chunk;
});
});
}
const data = await this.streamToString(response.data);
From a quick glance at axios' code, I couldn't find a place where it inspects the Content-length header, so perhaps this is done by Node's http? Is there a way to tell it to ignore Content-length and just read the entire stream until it closes (assuming HTTP keepalive is not used)?

Why is my no-cors fetch() not ok even if the request succeed?

I'm a complete Javascript beginner. I'm trying to poll a JSON for a status page with this code :
setInterval(refresh, 5000);
var beat_state = 0;
function refresh()
{
fetch("http://localhost:8080/", {headers: {"Accept": "application/json"}, mode: 'no-cors'}).then(
function(response) {
if (response.ok) {
document.getElementById("hearth").textContent = "❤️";
response.json().then(update_display);
} else {
document.getElementById("hearth").textContent = "💔️";
}
}
);
}
function update_display(json_health)
{
/* ... */
}
The server return this response :
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 186
Date: Sun, 06 Sep 2020 20:25:59 GMT
Server: lighttpd/1.4.55
{"socket_listening": true,"quick_shutdown": false,"workers_online": 20,"workers_sleeping": 19,"workers_backlog": 0,"connections": [{"id": 4,"active_requests": 1,"socket_insane": false}]}
I'm doing test with a standalone on-disk HTML page.
Given that the Firefox 80.0.1 console show that the request is successful with no error. Why is reponse.ok false ?
when you have mode:'no-cors'
you will get a response with type: "opaque"
which returns status:0
and since ok is only true on status in the range 200-299 you get ok:false
sources:
OK status
what type opaque does
opaque being response for no-cors
I would try to change the fetch syntax, it seems that you've done some nested ".then"s, that may cause the fetch not to work
In order to have the process run and catch errors, maybe something like this will work
setInterval(refresh, 5000);
var beat_state = 0;
function refresh()
{
fetch("http://localhost:8080/", {headers: {"Accept": "application/json"}, mode: 'no-cors'})
.then(function(response) { if (response.ok) {
document.getElementById("hearth").textContent = "❤️";
return response.json();
} else {
document.getElementById("hearth").textContent = "💔️";
}
})
.then(function(json) {
update_display();
}
.catch(error => {
console.log(error.message);
})

Getting error while fetching orders from salesforce sfcc

While executing the below code I am getting the token such format like Bearer {token}
Now While gitting the getOrderList() I am getting a 400 Bad Request error.
I am not sure what am I doing wrong? I am using this https://documentation.b2c.commercecloud.salesforce.com/DOC1/index.jsp?topic=%2Fcom.demandware.dochelp%2FOCAPI%2F15.2%2Fshop%2FResources%2FOrders.html as a reference to fetch all orders from the salesforce while is created recently.
Can anyone help me with this thing?
'use strict';
const fetch = require('node-fetch');
const ocapi_path = require('./ocapi_path');
const envDomain = 'Domainhere';
const envClientId = 'clientidHere';
const getToken = async (domain = envDomain, clientId = envClientId) => {
const response = await fetch(
`${domain}/s/site-id/dw/shop/v19_1/customers/auth?client_id=${clientId}`,
{
method: 'POST',
body: JSON.stringify({ type: 'guest' }),
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
},
},
);
if (!response.ok) {
const json = await response.json();
throw new Error(`OCAPI error response: ${JSON.stringify(json)}`);
}
return response.headers.get('Authorization');
};
const getOrderList = async (token) => {
const domain = envDomain;
const response = await fetch(
`${domain}/s/site-id/dw/shop/v19_1/orders?status=completed`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Cookie': token,
Authorization: token,
},
},
);
if (response.ok) {
return await response.json();
}
return null;
};
const getTheResult = async () => {
const token = await getToken();
const result = await getOrderList(token);
console.log(result);
}
getTheResult();
You need to exchange the access token for session credentials and then use those to call the Orders API.
Retrieve token for guest (you've done this)
Exchange token for session creds:
To obtain a session for a guest or registered customer
you have to pass a valid JWT to /sessions resource. The JWT has to be
passed as Authorization:Bearer request header. In case of success you
get the session cookies back.
REQUEST:
POST /dw/shop/v20_2/sessions HTTP/1.1
Host: example.com
x-dw-client-id: ...
Authorization: Bearer <token>
RESPONSE:
HTTP/1.1 204 NO CONTENT
Set-Cookie : dwsecuretoken_a85a5236a2e852d714eb6f1585efb61c=""; Expires=Thu, 01-Jan-1970 00:00:10 GMT;
Set-Cookie : dwsid=eXv5R3FZGI4BBfbK1Opk5s1mJ-41Aw7ZuaMKxeye5xa16fJMX--AnNkXsvmakbi1UZSzP1zoPmUILgoom1_jKg==;
Set-Cookie : dwanonymous_a85a5236a2e852d714eb6f1585efb61c=bdjalnzmfrkJ0FtYliwud5db67; Max-Age=15552000;
Cache-Control: max-age=0,no-cache,no-store,must-revalidate
Call Order API with session creds from previous step:
REQUEST:
GET /dw/shop/v15_2/orders?status=completed HTTP/1.1
Host: example.com
Cookie: dwsecuretoken_a85a5236a2e852d714eb6f1585efb61c="";dwsid=eXv5R3FZGI4BBfbK1Opk5s1mJ-41Aw7ZuaMKxeye5xa16fJMX--AnNkXsvmakbi1UZSzP1zoPmUILgoom1_jKg==; dwanonymous_a85a5236a2e852d714eb6f1585efb61c=bdjalnzmfrkJ0FtYliwud5db67;
Content-Type: application/json; charset=UTF-8
RESPONSE:
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
{
"_v" : "15.2",
"count" : ...,
"data" : [...],
...
}

Fetch answer empty due to the preflight?

I have an webapp react.js / redux / webpackt / es6... and an api in go with mux from gorilla.
When I make call with the function below my header is empty and content too.
I'm using this package in my webapp to make calls
"isomorphic-fetch": "^2.2.1",
My call example
export function Login(userData) {
return dispatch => {
fetch(API + '/login', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: userData.email,
password: userData.password,
}),
})
.then(response => {
console.log(response);
console.log(response.statusText);
console.log(response.status);
console.log(response.headers);
console.log(response.headers.get("Authorization"));
console.log(response.json());
return response.json()
if (response.status >= 200 && response.status < 300) {
console.log(response);
dispatch(LoginSuccess(response));
} else {
const error = new Error(response.statusText);
error.response = response;
dispatch(LoginError(error));
throw error;
}
}).then(function(json) {
console.log('parsed json' + json)
})
.catch(error => { console.log('request failed', error); });
}
In the beginning I had a problem with cors How to handle preflight CORS requests on a Go server I used this solution
We can look the call inside of the console :
login OPTIONS 200 fetch auths.actions.js:38 352 B 1 ms
login POST 200 json Other 567 B 82 ms
When I look inside of my POST Header response I have :
HTTP/1.1 200 OK
Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, PATCH, DELETE
Access-Control-Allow-Origin: http://localhost:3000
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0NTQ3NTcxNjEsInVzZXJfaWQiOiI1NmI1YjZlOTFhZTMzYjAwMDFhYmE1MTQifQ.WGoTMxm6OuN24Olwr93J3pND9dFLCtG5MyiRbqLWeD244JtDzq0bGgQMixeZxyuxwGK3u8KhyWD7Rr6iZAGNpA
Content-Type: application/json
Date: Sat, 06 Feb 2016 11:12:41 GMT
Content-Length: 2
So the response handle my preflight information not my POST ? Because there is nothing inside of the response.headers and response.headers.get("Authorization")
There is something wrong ?
I had the problem that my headers were sent, correctly received (chrome's network tab correctly shows me all the sent headers), but I couldn't access them in js (response.headers was empty). As described in Fetch get request returns empty headers, this happened because the server did not set the Access-Control-Expose-Headers header, resulting in the needed headers not to be exposed to js.
So the solution is to add this header on the server and voilà, now the headers are accessible in js:
Access-Control-Expose-Headers: <header-name>, <header-name>, ...
The header takes a comma-separated list of header-names to be exposed to the browser.
For additional info on why this header is needed, see Why is Access-Control-Expose-Headers needed?

Categories