How to make a REST GET request (with authentication) and parse the result in javascript?

半世苍凉 提交于 2019-12-25 09:34:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!