How can I convert this Ajax query to http client request in Angular 8? - ajax

I have a request in ajax, like this:
var data = {
REQUEST: 'GetFeatureInfo',
SERVICE: 'WMS',
VERSION: '1.1.1',
LAYERS: layerName,
STYLES: '',
FORMAT: 'image/png',
INFO_FORMAT:'application/json',
BGCOLOR: '0xFFFFFF',
TRANSPARENT: 'TRUE',
SRS: 'EPSG:' + mapSRID,
BBOX: xmin + "," + ymin + "," + xmax + "," + ymax,
WIDTH: map.width,
HEIGHT: map.height,
QUERY_LAYERS: layerName,
X: screenPoint.x.toFixed(0),
Y: screenPoint.y.toFixed(0)
};
$.ajax({
type: 'GET',
url: url,
data: data,
dataType: "application/json",
complete: function (data) {
callBack(data);
}
});
}
I want to convert to angular by using http client get method. How can I do that.
My solution but reponse: ok: false
getInfo() {
const params = {
SERVICE: 'WMS',
VERSION: '1.1.1',
...
};
this.http.get<any>('http://localhost:8080/geoserver/topp/wms', params).subscribe(data => {
console.log(data);
});
}
The response:
status: 200
statusText: "OK"
url: "http://localhost:8080/geoserver/topp/wms?SERVICE=WMS&VERSION=1.1.1&EQUEST=GetFeatureInfo&FORMAT=image/png&TRANSPARENT=true&QUERY_LAYERS=topp:states&LAYERS=topp:states&exceptions=application/vnd.ogc.se_inimage&INFO_FORMAT=text/html&FEATURE_COUNT=50&X=50&Y=50&SRS=EPSG:4326&STYLES=&WIDTH=101&HEIGHT=101&BBOX=-113.8623046875,42.4072265625,-104.9853515625,51.2841796875"
ok: false
To more clear, I'm want to convert URL get request to http client get method request in Angular 8:
http://localhost:8080/geoserver/wms?service=wms&version=1.1.1&request=GetCapabilities

Inject HttpClient to in your service.
this.http.post(url , data).subscribe(response => {
console.log(response);
}) //post request if you have to send data
this.http.get(url).subscribe(response => {
console.log(response);
})//get if you want data
Ajax internally append data you send with the request to the url string. So in order to do that using angular, you need to use HttpParams
let params = new HttpParams().set("paramName",paramValue).set("paramName2", paramValue2); //Create new HttpParams
this.http.get(url, {headers: headers, params: params});

In your data you have EQUEST instead of REQUEST

Related

Unable to upload pdf file in POST request using Cypress 6.4.0 & TypeScript

I am writing API tests using Cypress 6.4.0 & TypeScript where I need to upload a pdf file in the request body.
My code for the request is:
My code for the request body is:
public async createAssetDocTest() {
let url = sharedData.createAsset_url + sharedData.assetA;
let response = await fetch(url
,
{
method: 'POST',
body: await requestbody.createAssetDocBody(),
headers: {
Authorization: sharedData.bearer + " " + adminTokenValue,
Accept: sharedData.accept,
'Content-type': sharedData.docReqContent,
},
}
);
expect(response.status).to.equal(200);
public async createAssetDocBody(): Promise<any> {
const file = sharedData.doc;
cy.fixture(file).then((pdfDoc) => {
Cypress.Blob.binaryStringToBlob(
pdfDoc,
sharedData.contentTypeValue
).then(async (blob: string | Blob) => {
const formData = new FormData();
formData.set(sharedData.document, blob, file);
const body = {
formdata: {
document: {
value: pdfDoc,
options: {
filename: sharedData.document,
contentType: null,
},
},
},
};
return body;
});
});
}
However, the file does not upload the file & the request fails with error 400. Is there a better way to upload files in the body of the POST request?
enter image description here
Resolved this issue!
The main issue was that my Cypress version was too old. Upgraded to 9.7.0
Then added the following code:
public async createAssetDoc(): Promise<any> {
cy.fixture("pic location", "binary")
.then((file) => Cypress.Blob.binaryStringToBlob(file))
.then((blob) => {
var formdata = new FormData();
formdata.append("document", blob, "pic location");
const url = "your url";
cy.request({
url,
method: "POST",
body: formdata,
headers: {
Authorization:
"bearer" + " " + token,
Accept: "application/json",
"Content-Type": "multipart/form-data",
},
}).then((response) => {
expect(response.status).to.equal(201);
expect(response.statusText).to.equal(
sharedData.fileUploadStatusText
);
const finalResponse = String.fromCharCode.apply(
null,
new Uint8Array(response.body)
);
return finalResponse;
});
});
}

Cypress: How do I pass a selected property from API response to another API request?

I would like to use Cypress for API testing. My goal is to extract a part of the API response and pass it to another API request. Here's a sample code:
Cypress.Commands.add('createCustomer', () => {
return cy.request({
method: 'POST',
url: 'api/v1/Customers',
headers: {
'Content-Type': 'application/json'
},
body: {
// sample content
}
}).then((response) => {
return new Promise(resolve => {
expect(response).property('status').to.equal(201)
expect(response.body).property('id').to.not.be.oneOf([null, ""])
const jsonData = response.body;
const memberId = jsonData.id
resolve(memberId)
return memberId
})
})
})
With this code, I am getting [object%20Object] as the result.
Hoping for some feedback.
So you are adding the id generated by the POST to a subsequent GET request?
Try returning the id without using a Promise, I don't think you need one at that point since the response has already arrived.
}).then((response) => {
expect(response).property('status').to.equal(201)
expect(response.body).property('id').to.not.be.oneOf([null, ""])
const jsonData = response.body;
const memberId = jsonData.id;
return memberId;
})
Url for GET
cy.createCustomer().then(id => {
const url = `api/v1/Customers${id}`;
...
or
cy.createCustomer().then($id => {
const id = $id[0]; // Not quite sure of the format, you may need to "unwrap" it
const url = `api/v1/Customers${id}`;
...
If you want to pass response from API Request 1 to API Request 2, you can do something like this:
describe('Example to demonstrate API Chaining in Cypress', function () {
it('Chain two API requests and validate the response', () => {
//Part 1
cy.request({
method: 'GET',
url: 'https://www.metaweather.com/api/location/search/?query=sn',
}).then((response) => {
const location = response.body[0].title
return location
})
//Part 2
.then((location) => {
cy.request({
method: 'GET',
url: 'https://www.metaweather.com/api/location/search/?query=' + location
}).then((response) => {
expect(response.status).to.eq(200)
expect(response.body[0]).to.have.property('title', location)
})
})
})
})
Your code seems to be failing during the initial request, not during the subsequent actions. I am far from a Javascript expert, but you seem to have some unnecessary complexity in there. Try simplifying your command like this and see if you can at least get a successful request to go through:
Cypress.Commands.add('createCustomer', () => {
cy.request({
method: 'POST',
url: 'api/v1/Customers',
headers: {
'Content-Type': 'application/json'
},
body: {
// sample content
}
})
})
And if that works, keep going:
Cypress.Commands.add('createCustomer', () => {
cy.request({
method: 'POST',
url: 'api/v1/Customers',
headers: {
'Content-Type': 'application/json'
},
body: {
// sample content
}
}).then((response) => {
expect(response).property('status').to.equal(201)
expect(response.body).property('id').to.not.be.oneOf([null, ""])
const jsonData = response.body;
const memberId = jsonData.id
return memberId
})
})

Openvidu server API REST with fetch

I start up KMS+OPENVIDU server with docker. Everything works nice with web component when i use JQ ajax:
For example (this works fine):
$.ajax({
type: "POST",
url: OPENVIDU_SERVER_URL + "/api/sessions",
data: JSON.stringify({ customSessionId: sessionId }),
headers: {
"Authorization": "Basic " + btoa("OPENVIDUAPP:" + OPENVIDU_SERVER_SECRET),
"Content-Type": "application/json"
},
success: response => resolve(response.data.id),
error: (error) => {
if (error.status === 409) {
resolve(sessionId);
} else {
console.warn('No connection to OpenVidu Server. This may be a certificate error at ' + OPENVIDU_SERVER_URL);
if (window.confirm('No connection to OpenVidu Server. This may be a certificate error at \"' + OPENVIDU_SERVER_URL + '\"\n\nClick OK to navigate and accept it. ' +
'If no certificate warning is shown, then check that your OpenVidu Server is up and running at "' + OPENVIDU_SERVER_URL + '"')) {
location.assign(OPENVIDU_SERVER_URL + '/accept-certificate');
}
}
}
})
If i put fetch (native javascript) :
var myPromise = fetch(this.ovServerUrl + '/api/sessions', {
method: 'POST',
// mode: 'cors',
// credentials: 'same-origin',
// redirect: 'follow',
body: JSON.stringify(
{ customSessionId: sessionId }
),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa('OPENVIDUAPP:' + this.ovSecret)
}
})
return myPromise.then(response => {
console.log('return resolve !response', response)
console.log('return resolve !response.data.id! ', response.data.id)
return response.id
})
I got response but without response.id .
Looks like :
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "cors"
url: "https://MY_DOMAIN:4443/api/sessions"
Any suggestion ?

How to post json data to order an item using woocommerce api using ajax with authentication

I have tried 2 types of ajax calls to post json data so that i can order an item using woocommerce API. I am using OAuth1.0a to authorize the user. Its getting the data but not able to post the data. But none of them worked for me. So please somebody say how to post json data using ajax call. Thanks in advance.
var oauth2 = OAuth({
consumer: {
public: 'key',
secret: 'secret'
},
signature_method: 'HMAC-SHA1'
});
var token = {
public: 'key',
secret: 'secret'
};
var dataToSend = {};
var request_data = {
url: 'http://www.example.com/wc-api/v3/orders',
method: 'POST',
data: dataToSend
};
return $.ajax({
url: request_data.url,
type: request_data.method,
data: oauth2.authorize(request_data, token)
});
return $.ajax({
url: request_data.url,
type: request_data.method,
'content-type': 'application/json',
body: request_data.data,
headers: oauth2.toHeader(oauth2.authorize(request_data, token))
});
dataToSend - Example Data
key is genetrated using below link :
https://docs.woothemes.com/document/woocommerce-rest-api/
Just simply see all the headers in the oauth2.authorize(request_data, token)
and simply add all those headers to the url after '?'...That's the solution i had...
var generatedoauth = oauth.authorize(request_data, token);
console.log("oauth " + JSON.stringify(generatedoauth));
var newUrl = '<Url Goes Here>';
var paramsSt = '?oauth_consumer_key=' + generatedoauth.oauth_consumer_key + '&oauth_nonce=' + generatedoauth.oauth_nonce + '&oauth_signature_method=' + generatedoauth.oauth_signature_method + '&oauth_timestamp=' + generatedoauth.oauth_timestamp + '&oauth_signature=' + generatedoauth.oauth_signature;
newUrl = newUrl + paramsSt;`

Post jQuery JSON Object to NodeJs Restify

I want to know why it is so hard to post a simple JSON string in a /:parameter to restify. I have followed many examples but have not found anything concrete.
I have the following code in the front end.
$("#btnDoTest").click(function() {
var jData = {
hello: "world"
};
var request = $.ajax({
url: "http://localhost:8081/j/",
async: false,
type: "POST",
data: JSON.stringify(jData),
contentType: "application/javascript",
dataType: "json"
});
request.success(function(result) {
console.log(result);
});
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
I am succesful in sending simple text if I concatenate the param after the j/. But what I want to send is an object like this {hello:"world"} and reconstruct it back in nodeJS and work with it.
--Edit:
This is my nodejs file
/* the below function is from restifylib/response.js */
var restify = require("restify");
/* create the restify server */
var server = restify.createServer({
});
server.use(restify.bodyParser({ mapParams: true }));
server.use(
function crossOrigin(req,res,next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
return next();
}
);
server.post('/j/', function (req, res, next) {
//res.send(201,"REceived body: "+JSON.stringify(req.params));
res.send(201,"REceived body: "+JSON.stringify(req.params));
return next();
});
var port = 8081;
server.listen(port);
console.log("Server listening on port " +port)
Any help would be appreciated thanks.
0x
I finally got it working.
--Front end code
$("#btnDoTest").click(function() {
var request = $.ajax({
url: "http://localhost:3000/j",
async: false,
type: "POST",
data: {
blob: {wob:"1",job:"2", ar:[1,2,{a:'b'}]}
},
contentType: "application/x-www-form-urlencoded", //This is what made the difference.
dataType: "json",
});
request.success(function(result) {
console.log(result);
});
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
NodeJs services
/* the below function is from restifylib/response.js */
var restify = require("restify");
/* create the restify server */
var server = restify.createServer({
});
server.use(restify.bodyParser());
server.use(restify.CORS());
server.post('/j/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
// req.params == data on jquery ajax request.
res.send(200, JSON.stringify(req.params));
console.log(req.params.blob.ar[2].a)
res.end();
return next();
});
var port = 3000;
server.listen(port);
console.log("Server listening on port " + port)
Don't stringify it. Try this, note the two changes, I removed the JSON.stringify and switched to application/json, as its JSON and not JavaScript.
var request = $.ajax({
url: "http://localhost:8081/j/",
async: false,
type: "POST",
data: jData,
contentType: "application/json",
dataType: "json"
});
application/javascript should only be used when doing JSONP.
my answer first!
jquery:
$.ajax({
url: url,
method: 'post',
data: JSON.stringify({key:value}),
contentType: "application/json"
});
node http:
server.post('/1', function(req, res) {
var body = req.body;
var dataValue = body.dataKey;
});
why?
data of $.ajax is just for what to send to server end, its datatype has not be defined, so when use JSON.stringify({key:value}), the data will be sent as a string like '{key:"xxx"}', and node recieve a string, not a json object even the string structure looks like a json. but after we add contentType: "application/json" in $.ajax, when node recieve the data, it will be a real json object type data.

Resources