javascript fetch to IP address without http in url - fetch

I need to post data to local IP address with fetch like this:
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/xml");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("192.168.1.5:11443", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
But fetch thinks it is not absolute address so id adds prefix. I cannot add http because server doesnt accept it.
I am using postman and it works there but cant make it work in my frontend.

If you want to use an absolute address, you need to have protocol:// (http:// for instance), unless it's the same protocol as the current one (i.e. the one of your website), in which case you can simply use //.
Try this: //192.168.1.5:11443, that will be evaluated to http://192.168.1.5:11443 if your website runs with HTTP and https://192.168.1.5:11443 if it runs with HTTPS.

Related

Cypress: How to access the body of a POST-request?

Is there a way in Cypress to check the body of a POST-request?
E.g.: I have entered some data in a form, then pressed "Submit".
The form-data is send via POST-request, separated by a blank line from the header-data.
I would like to check the form-data. If all data, which I have entered, are included and if they are correct.
Is that possible with Cypress?
cy.get('#login').then(function (xhr) {
const body = xhr.requestBody;
console.log(xhr);
expect(xhr.method).to.eq('POST');
});
The xhr-object doesn't have the transferred data included.
It should be possible.
describe('Capturing data sent by the form via POST method', () => {
before(() => {
Cypress.config('baseUrl', 'https://www.reddit.com');
cy.server();
cy.route({
method: 'POST',
url: '/login'
}).as('redditLogin');
});
it('should capture the login and password', () => {
cy.visit('/login');
cy.get('#loginUsername').type('username');
cy.get('#loginPassword').type('password');
cy.get('button[type="submit"]').click();
cy.wait('#redditLogin').then(xhr => {
cy.log(xhr.responseBody);
cy.log(xhr.requestBody);
expect(xhr.method).to.eq('POST');
})
});
});
This is how you can inspect your data in Chrome Developer Tool.
You should see the same thing you've seen from Chrome Developer Tool when you run your test in Cypress.
I was Googling the same problem and somehow landed here before reaching the documentation.
Anyway, have you tried something like:
cy.wait('#login').should((xhr) => {
const body = xhr.request.body
expect(body).to.match(/email/)
})
I haven't tested it out with a multipart/form-data encoded request, but I suspect that you'll also find the request body that way.
Good luck!
It's better to use cy.intercept() in order to spy, stub and assert network requests and responses.
// assert that a request to this route
// was made with a body that included 'user'
cy.wait('#someRoute').its('request.body').should('include', 'user')
// assert that a request to this route
// received a response with HTTP status 500
cy.wait('#someRoute').its('response.statusCode').should('eq', 500)
// assert that a request to this route
// received a response body that includes 'id'
cy.wait('#someRoute').its('response.body').should('include', 'id')
Link to the docs

angular5 how to make asyc request?

In my project i made multiple request to server to get data for single page. I want to make all request asyc. Right now until i get the response from first request,the response of second request is not load.
So basically i just want to achive asyc request and response so one request will not wait for other request to finish.
Right now it's like first come first serve fashion.
But i want from multiple request which request get first response should load first.
this is code of my component
constructor(private _dashboardService: DashboardService) {
this.getLineChart();
this.todayPaymentDetails();
this.todayPaymentMethod();
this.rewardCustomers();
this.getAverageBill();
this.getItemByVolumn();
this.getItemBySales();
}
todayPaymentMethod(id=null){
this.paymentMethodsLoader=0;
this._dashboardService.getTodayPaymentMethod(id).subscribe(res =>{
if(null != res.data && '' != res.data){
this.location = res.data.location;
this.payment_methods = res.data.payment_methods;
}
this.paymentMethodsLoader=1;
});
}
this is my service code:
getTodayTotalPayment(id) : Observable<any> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.get(environment.apiUrl + constants.API_V1 + 'today-total-payment/'+id, options)
.map(res => res.json())
.catch((error: any) => Observable.throw(error.json().error || error));
}
Here shows code for only one request but as shown in constructor i send multiple request at a time.
FIrst it is not a good practise to call function like this in constructor.
For running multiple request or observable together use operators i.e. switchMap etc.
Follow this video link related to event loop in JavaScript this will improve your JavaScript execution , event loop concepts . also explains how asynchronous code executed.
Hope it will help.

How to deal with OPTION request?

I have the following code:
window.fetch(myServerURL, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(app.jsonRequest)
})
.then(res => res.json())
.then(json => {
if (json.affectedRows === 1) {
okMessage("Be welcome and check your email!");
} else {
errorMessage('Sorry! Please try again later.');
}
})
which is entitled to send a post message to my backend server and register a new user to my system using a MySQL database. And this is working fine, but my messages are not showing.
(Yes, I konw I should test more than just json.affectedRows to make sure the register was inserted fine, but I am simplifying the problem to make things clear here.)
It happens than I am detecing a preflight request OPTIONS and this is making my logic blow away, 'cause it seems it receives the OPTIONS answer first and do NOT have an affectedRows to compare. In fact, the OPTIONS request generates just OK, since server-side is configured with CORS.
On the other hand, when I write
.then(json => {
console.log(json);
}
to try to capture this OK answer to the OPTIONS request, the answer is
{"fieldCount":0,"affectedRows":1,"insertId":1845,"serverStatus":2,"warningCount":0,"message":"","protocol41":true,"changedRows":0}
as if there had been no OPTIONS request.
After trying other possible solutions with no success, Id would like to ask you all how should I deal with this in order to get my messages shown?

Getting 401 on API but working with postMan

I have this API:
const url = url;
const headers = new Headers({
"Content-Type": "application/json",
"Accept": "application/json", // change to application/javascript for jsonp
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": true,
"access_token": accessToken,
"id_token": idToken,
});
const options = {
method: "GET",
headers: headers,
credentials: "same-origin",
mode: "no-cors"
};
fetch(url, options)
.then(function(response) {
console.log('-working: ',response.json());
})
.catch(function(error) {
console.log('-error: ',error);
});
Having the same API on postMan this works like a charm there but on my code I always get 401 (Unauthorized).
Also if I remove "no-cors" I get a 401 plus CORS issue
I was having the same issue.
My senior said, that CORS is not safe, so first compare the headers of both the requests.
I would suggest you use Wireshark to see the the header that is being sent from both the requests.
Steps(step 3 and 4 is for conveniently spotting your requests):
Install Wireshark.
Select the network connection that you are using for the calls(for eg, select the Wifi if you are using it)
There will be many requests and responses, close extra applications.
Usually the requests are in green color, once you spot your request, copy the destination address and use the filter on top by
typing ip.dst==52.187.182.185 by putting the destination address.
Tap on your request made by postman and by your call.
Compare both the headers.
In my case, I was calling the API from my react native app, and the header parameter was getting converted into lowercase automatically.
So, to correct it, I made the parameter in lowercase in backend server.
Play "Spot the difference" between the two windows and find yours.
If this doesn't work, go with setting up CORS.
CORS needed to be added as an additional header on the back end

How to access Response cookies in angular2?

I'm trying to access this cookies (the response ones):
When I open the request in the chrome debug tools in the network section I can clearly see that the cookies are present, but how can I access those values from my code? I've never worked with cookies before and I don't know what to do to "extract" them... I'm working on a Ionic2 project using Http.
I've read that the allowCredentials: true header has to be sent but that didn't work...
Here's the request/response details:
Here's the service:
public callLogin(service_guid: string, pos_guid: string, login_data: Object) {
return this.http.post(
this.url + service_guid + "/" + pos_guid + "/ack",
login_data,
{withCredentials: true}
)
.map(response => response.headers);
}
And the caller:
this.__posService.callLogin(login_data.service_guid, login_data.pos_guid, {"password": data.password})
.subscribe(
res => {
console.log("Success:");
console.log(res.get("apsession"); // this returns undefined
},
err => {
console.log("Error:");
}
);
When I try to access the cookie from the header it returns undefined. What am I doing wrong here?
The name of the response header you are trying to get is actually Set-Cookie not apsession. So if you did something like res.get("set-cookie") it would return the first header that matched that name. Since you have more than 1, you could do:
let headers: Headers = res.headers;
headers.getAll('set-cookie');
which returns a list of all headers with that name. You could find apsession in there probably.
See:
https://angular.io/docs/ts/latest/api/http/index/Headers-class.html
https://developer.mozilla.org/en-US/docs/Web/API/Response/headers
https://developer.mozilla.org/en-US/docs/Web/API/Headers

Resources