I have a web service written is ASP.NET which when tested with Postman with JSON content works fine. JSON is sent as Body is Postman
When trying to implement the same in Nativescript using HTTP Post, it fails.
When checking the IIS logs, the cs-method for Postman is correct as POST, but the cs-method for my Nativescript code is GET. An example from the IIS log entry is below:
2019-07-01 12:42:52 xxx.xxx.xxx.xxx GET /Service.asmx/SaveAnswers -
443 - xxx.xxx.xxx.xxx
Mozilla/5.0+(Macintosh;+Intel+Mac+OS+X+10_13_6)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Brackets/1.14.0+Chrome/51.0.2704.103+Safari/537.36
- 200 0 0 62 2019-07-01 12:57:19 xxx.xxx.xxx.xxx POST /Service.asmx/SaveAnswers - 443 - xxx.xxx.xxx.xxx PostmanRuntime/7.15.0 -
200 0 0 359
My code to upload the JSON text is:-
function uploadJson(jsontxt){
console.log(jsontxt);
http.request = ({
url: "https://myURL/Service.asmx/SaveAnswers",
method: "POST",
headers: {"Content-Type": "application/json"},
content: jsontxt
}).then((response) => {
// var result = response.content.toJSON();
// console.log(result);
console.log("Finished upload");
}, (e) =>{
console.log("JSON upload error: "+e);
})
}
Changed the log IP address and my URL for security. I do not get any errors but do not understand how postman is POST and my script is GET in the logs
Related
I am trying to send an HTTP Post request from my test method to my Pactnet mock service. The following is the log generated -
[INFO][pact_mock_server::hyper_server] Received request HTTP Request ( method: POST, path: /api/v1/post-txn, query: None, headers: Some({"host": ["127.0.0.1:62047"], "content-length": ["160"], "content-type": ["application/json; charset=utf-8"]}), body: Present(160 bytes, application/json;charset=utf-8) )
[INFO][pact_matching] comparing to expected HTTP Request ( method: POST, path: /api/v1/post-txn, query: None, headers: Some({"Content-Type": ["application/json; charset=utf-8"]}), body: Present(114 bytes, application/json) )
For me, it looks like the received request and the expected request look the same from the log information. However, the test is unsuccessful with the below exception message -
{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Access-Control-Allow-Origin: *
x-pact: Request-Mismatch
Date: Thu, 24 Mar 2022 05:16:31 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 648
}}
Could someone help me what is wrong with my received request and expected request, and where there is a mismatch as mentioned in the exception details? I have spent a lot of time debugging, yet I am unable to find what exactly the issue is. Thanks in advance.
If you increase the log level to debug you should be able to compare the JSON body in the request to what's expected. The body looks to be different as I dictated by the number of bytes expected vs actual.
Additionally, there should be an error message to indicate why it failed. If not that could be a bug.
The header content type also looks different on close inspection
I am struggling to get an ionic this.http.post to work.
If I use this curl in my terminal it works great:
curl -v -X POST \
https://myuser-name:ijF3Ui7VYVbbSejmwsnVVo#appdb.mysite.com:5984/_session \
-d 'name=app&password=ijF3Ui7VYVbbSejmwsnVVo'
It gives me the following output:
Note: Unnecessary use of -X or --request, POST is already inferred.
* Trying 37.1.96.50...
* TCP_NODELAY set
* Connected to app.mysite.com (37.1.96.49) port 5984 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
* Server certificate: app.mysite.com
* Server certificate: COMODO RSA Domain Validation Secure Server CA
* Server certificate: COMODO RSA Certification Authority
* Server auth using Basic with user 'myuser-name'
> POST /_session HTTP/1.1
> Host: app.mysite.com:5984
> Authorization: Basic cDpkTUQySzg0a2lqRjNVaTdWWVZiYlNlam13c25WVm8=
> User-Agent: curl/7.54.0
> Accept: */*
> Content-Length: 52
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 52 out of 52 bytes
< HTTP/1.1 200 OK
< Set-Cookie: AuthSession=ZWhzLWFwcDo1OUFENThGRjruBtcPzHcqc1sC9WXrcWI7R27_Mg; Version=1; Secure; Path=/; HttpOnly
< Server: CouchDB/1.6.1 (Erlang OTP/18)
< Date: Mon, 04 Sep 2017 13:45:35 GMT
< Content-Type: text/plain; charset=utf-8
< Content-Length: 43
< Cache-Control: must-revalidate
<
{"ok":true,"name":null,"roles":["_admin"]}
* Connection #0 to host app.mysite.com left intact
My ionic POST code looks like this:
login(callerName:string):any
// Make sure we have a CouchDB session so that PouchDB can access the CouchDB database
{
console.log('Authentication: login(): Login function called from ' + callerName);
return new Promise(resolve => {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let credentials = {
name: COUCHDB_USER,
password: COUCHDB_PASSWORD
};
let result = {
success: false,
data: []
};
console.log('Authentication: login(): credentials = ' + JSON.stringify(credentials));
// NOTE:
//
// If POST is called with COUCHDB_SERVER with no auth in the url I get the error: Response with status: 401 Unauthorized for URL: https://app.mysite.com:5984/_session"
//
// If POST is called with COUCHDB_SERVER WITH auth in url I get the error: Response with status: 0 for URL: null
// This 'might' mean:
// Timeout from server
// Request not sent
// Requesting an unreachable url
// ...
// This WORKS with curl in terminal
//
// With auth in url: https://myuser-name:ijF3Ui7VYVbbSejmwsnVVo#app.mysite:5984/_session
// Without auth in url: https://app.mysite.com:5984/_session
//
this.http.post(COUCHDB_SERVER + '/_session', JSON.stringify(credentials), {headers: headers})
.subscribe(res => {
var details = res.json();
console.log('Authentication: login(): SuperLogin successful login: res = ' + JSON.stringify(details));
result.success = true;
result.data = details;
resolve(result);
},
(err) => {
console.log('Authentication: login(): Login failed err = ' + err);
let details = err.json();
result.success = false;
result.data = details;
resolve(result);
});
});
}
If I try the POST in ionic with no auth in the url I get a sensible error message:
Response with status: 401 Unauthorized for URL: https://app.mysite.com:5984/_session"
But if I add auth to the url I get an error message that doesn't tell me what the problem is:
Response with status: 0 for URL: null
I can't work out why it works with curl but not within ionic http.post.
I have the same problem whether I run ionic serve or I run the app on an iPhone.
UPDATE
I have run the ionic App in Chrome and now have a better error:
error: "unauthorized", reason: "Authentication required."
So it is clear I am not getting the POST request correct but can't see why.
The authentication failed in ionic because the usage of this.http.post is incorrect: the second parameter should be HTTP request body object (JSON, the credential object), not a string. Please refer to https://angular.io/guide/http for example.
The code to send HTTP request would be:
this.http.post(COUCHDB_SERVER + '/_session', credentials, {headers: headers})...
It works in curl, but not in ionic -- That's because the Content-Type of the HTTP request sent by curl is application/x-www-form-urlencoded, and curl's syntax is correct.
Shall I add auth to the URL? -- I guess it means the myuser-name:ijF3Ui7VYVbbSejmwsnVVo# part in the URL. The answer is No: It works in curl (add Authorization header in request) but it won't work in browser, please check Pass username and password in URL for HTTP Basic Auth for details.
Update: It seems Basic authentication is forced in CouchDB. In order to satisfy it, Authorization header can be added manually in HTTP request:
headers.append('Authorization', 'Basic ' + window.btoa(username + ':' + password))
For the last few weeks, we started getting CORS errors when trying to retrieve the auth token v2 API. We installed chrome CORS plugin and got that to work for now but then the flight fares API started giving CORS errors, we tried providing the regular cors headers in the request but to no avail. here is what is seen in the developer console. I am sending a GET request for the flight fares and tried the regular CORS headers as well but to no avail..
var getFlightFares = {
method: 'GET',
url: mainURL + "/v2/shop/flights/fares",
headers: {
'Authorization': 'Bearer '+token,
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': "/"
//'Access-Control-Allow-Origin': '*',
//'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
//'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
}
};
Result in developer console
GET
http://127.0.0.1:8080/spa/images/flights/sm%7B%7Bcheckout1.returnAirlineCode%7D%7D.gif [HTTP/1.1 200 OK 0ms]
OPTIONS
XHR
https://api.test.sabre.com/v2/auth/token [HTTP/1.1 200 OK 623ms]
POST
XHR
https://api.test.sabre.com/v2/auth/token [HTTP/1.1 200 OK 152ms]
Response :
Object { data: Object, status: 200, headers: dd/<(), config: Object, statusText: "OK" } sabre_integration.js:311:5
tokenT1RLAQJyP+PPcbBSEiIy9JBZrGkt4nu/dBD6CkzcyWI0njOM/Bbn3ngcAADA961ZaE1tN5y/bu57k0DseB5ocYDY9AIj64EwVJOr4RYAHKZF+H8tL7QnM35wjKYr40yjxkp1XL8lRDx84B+whxOMTaDreGnp1tDtFPhCGilvfeFpuXawbf1PjWAsR0uoNE9c0Pnmk8qWwuYEgNEkODYs8+K/peXF97LqylCFC6MWmkyodwSGwH7D/hjD5wTcSqJGLvARwo2NY/hplnArn8rY3sZ9gN3JV5PhqyPks56PYyD0Y5WvABg8YOVEA/Ud sabre_integration.js:312:5
OPTIONS
XHR
https://api.test.sabre.com/v2/shop/flights/fares [HTTP/1.1 404 Not Found 100ms]
Headers
Params
Response
departuredate2016-12-06destinationLAXlengthofstay5originJFKpointofsalecountryUS
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.test.sabre.com/v2/shop/flights/fares?origin=JFK&destination=LAX&departuredate=2016-12-06&lengthofstay=5&pointofsalecountry=US. (Reason: CORS preflight channel did not succeed). (unknown)
GET
http://127.0.0.1:8080/spa/images/flight_listing_sprite.png [HTTP/1.1 200 OK 33ms]
Try opening google chrome from command prompt with the commands:
"chrome.exe --disable-web-security --user-data-dir=/path/to/foo"
check there then
Ok, so it seems pretty easy in Node.js to get the hostname of the request being made to my server:
app.get('/', function(req,res){
console.log(req.headers.host);
});
Is there an easy way to determine the hostname of my actual http server? For example, my server is running at the address http://localhost:3000 - can I programatically determine this address? I am using expressjs.
Yes you can using the;
var express = require('express'),
app = express(),
server = require('http').createServer(app);
server.listen(3000, function(err) {
console.log(err, server.address());
});
should print
{ address: '0.0.0.0', family: 'IPv4', port: 3000 }
you can also retreive the hostname for the os by the following;
require('os').hostname();
I have this NodeJS snippnet :
require('http').get({
secure: true,
host: 'github.com',
method: 'GET',
path: '/downloads/Graylog2/graylog2-web-interface/graylog2-web-interface-0.9.6.tar.gz',
'headers': {
Host: 'github.com'
}}).on('response', function(response) {
console.log(response.statusCode);
});
It is suppose to do a simple GET request on https://github.com/downloads/Graylog2/graylog2-web-interface/graylog2-web-interface-0.9.6.tar.gz (sample)
The problem I face is the HTTP status, using the NodeJS client I have 301 Moved Permanently. I am expected a 302 Found (actually what I get with Chrome, cUrl, http://web-sniffer.net,...).
Thanks
There is no secure option for request. What you want is to instead use the https module.
require('https')