Cross domain requests in server-side Dart

风流意气都作罢 提交于 2020-01-26 04:28:04

问题


I write a bunch of scripts in javascript and want to switch to dart or at least start using it. I do have one question though: i know js doesn't support x-domain requests in the browser, but what about running a dart application/script from the server, is it still the same? can this even be done?

basically, since i have no access to the web server to which i query, cross domain ability is a big necessity.


回答1:


It sounds like you might be asking about writing a server side command line script which can make requests to an HTTP server. Though the wording of question isn't totally clear to me. (The answers above are about browser based Dart scripts.)

This is possible with Dart. There are no cross origin restrictions in this case.

See the HttpClient class. Or you can use the http package on pub.

I recommend using the http package, as it provides a simpler high-level interface.

Here is an example using the http package:

import 'dart:io';
import 'package:http/http.dart' as http;

main() {
    http.read("http://google.com").then((content) {
        print(content);
    });
}

You'll need to update your pubspec.yaml file to add the following dependencies:

name: Http Example
   dependencies:
     http: any
     pathos: any

(Actually, you should only need to include http, but I think the http package is missing the pathos dependency in it's pubspec.yaml file.)

I couldn't find the pretty documentation for http, but there is some doc comments in the source file.




回答2:


Cross domain security is built into the browser, so is neither a feature of Dart or JavaScript.

Useful for testing: you can pass flags into chrome that will disable this security feature. See here: http://joshuamcginnis.com/2011/02/28/how-to-disable-same-origin-policy-in-chrome/

If you want to do a GET request, then you can use Dart JavaScript interop, see this section in this article: http://www.dartlang.org/articles/json-web-service/#note-on-cors

If you want to POST requests on the other hand, you'll run into problems unless the target server supports CORS. More details here: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

Edit: The correct approach would be to have your client-side code communicate with a server you own, and have that server communicate with the third-party server.




回答3:


You can enable cross-origin requests on the server by setting the Access-Control-Allow-Origin header on the http response. The value is either * to allow any origin to access the resource, but it is definitely safer to specify valid origins.



来源:https://stackoverflow.com/questions/15556942/cross-domain-requests-in-server-side-dart

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