问题
Due to circumstances beyond my control, Javascript
is the only language option available for me. I'm a beginner and am not even sure if I'm approaching the problem in a "recommended" manner.
Simply put, a customer has setup a MarkLogicDB
server online and has given me read-only access. I can query the server with the HTTP GET protocol to return an XML
document that has to be parsed. I've been able to create a curl
command to return the data I need (example below);
curl --anyauth --user USERNAME:PASSWORD \
-X GET \
http://test.com:8020/v1/documents?uri=/path/to/file.xml
The above returns the requested XML
file. Can someone please show me how I could convert the above to javascript
code? Additionally, how would I parse the data? Let's say I want to get all the info from a certain element or attribute. How can this be accomplished?
This would be trivial for me to do in Java/.NET
, but after reading plenty of online tutorials on Javascript, my head is spinning. Every tutorial talks about web-browsers, but I'm doing this on a server environment (The parse.com CloudCode). There isn't any UI or HTML involved. For debugging, I just read the logs created with console.log()
.
回答1:
https://parse.com/docs/cloud_code_guide#networking seems pretty clear, as far as it goes.
Parse.Cloud.httpRequest({
url: 'http://test.com:8020/v1/documents',
params: {
uri : '/path/to/file.xml'
},
success: function(httpResponse) {
console.log(httpResponse.text);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
}
});
But you'll also need authentication. The Parse.Cloud.httpRequest
docs don't include any examples for that. If you have support with that vendor, ask the vendor about digest authentication.
If you're stuck you might try adding user
and password
to the httpRequest
params and see what happens. It might work, if the developers of this stack followed the XMLHttpRequest convention.
Failing support from the vendor and existing functionality, you'll have to implement authentication yourself, in JavaScript. This works by generating strings that go into the request headers. These resources should help:
- http://en.wikipedia.org/wiki/Digest_access_authentication
- http://en.wikipedia.org/wiki/Basic_access_authentication
Basic auth is much easier to implement, but I'd recommend using digest for security reasons. If your HTTPServer doesn't support that, try to get the configuration changed.
来源:https://stackoverflow.com/questions/21426137/how-to-make-a-rest-get-request-with-authentication-and-parse-the-result-in-jav