CORS与Dart,我如何让它工作? [英] CORS with Dart, how do I get it to work?
问题描述
刚开始修改Dart,我决定写一个简单的Http服务器和客户端。我的服务器代码:
Just started tinkering with Dart and I decided to write a simple Http Server and a client. My server code:
#import("dart:io");
final HOST = "127.0.0.1";
final PORT = 8080;
final LOG_REQUESTS = true;
void main() {
HttpServer server = new HttpServer();
server.addRequestHandler((HttpRequest request) => true, requestReceivedHandler);
server.listen(HOST, PORT);
print("Server is running on ${PORT}.");
}
void requestReceivedHandler(HttpRequest request, HttpResponse response) {
var pathname = request.uri;
var apiresponse="";
if (LOG_REQUESTS) {
print("Request: ${request.method} ${pathname}");
}
if(pathname == '/api'){
response.headers.set(HttpHeaders.CONTENT_TYPE, "text/plain; charset=UTF-8");
response.headers.add("Access-Control-Allow-Methods", "POST, OPTIONS, GET");
response.headers.add("Access-Control-Allow-Origin", "*");
response.headers.add('Access-Control-Allow-Headers', '*');
print('welcome to the good life');
response.outputStream.writeString("API Call");
response.outputStream.close();
}
}
我的客户代码:
#import('dart:html');
#import('dart:json');
class dartjson {
dartjson() {
}
void run() {
write("Hello World!");
}
void fetchFeed(){
XMLHttpRequest xhr = new XMLHttpRequest();
var url = "http://127.0.0.1:8080/api";
xhr.open("GET", url, true);
xhr.setRequestHeader('Content-Type', 'text/plain');
//xhr.setRequestHeader('Access-Control-Request-Headers', 'http://127.0.0.1:3030');
xhr.send();
print(xhr.responseText);
document.query('#status').innerHTML = xhr.responseText;
}
void main() {
new dartjson().fetchFeed();
}
我一直收到错误:
XMLHttpRequest cannot load http://127.0.0.1:8080/api. Origin
http://127.0.0.1:3030 is not allowed by Access-Control-Allow-Origin.
我做错了什么?
推荐答案
你可以简化你的生活和运行服务器/客户端脚本从同一主机:端口地址。 http://www.dartlang.org/articles/io上有一个小型网络服务器示例/#web-servers ,它也提供静态文件。添加您的'/ api'处理程序并确保您的客户端文件在同一目录中。示例服务器比在端口3030上运行的Dart Editor内置服务器慢得多。
you could simplify your life and run both server/client scripts from the same host:port address. There is a small webserver example at http://www.dartlang.org/articles/io/#web-servers that serves static files too. Add your '/api' handler and make sure your client files are in the same directory. The example server is a lot slower than the Dart Editor builtin server that runs on port 3030.
这篇关于CORS与Dart,我如何让它工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!