英文:
Can't run GolLang backend with dart and angular2 client
问题
我使用这个教程来制作一个使用GoLang、Angular2和Dart的Web应用程序,但是当我通过控制台命令"backend"启动后端,并在浏览器中路由到"localhost:8080/"时,它应该调用Dart类"Hello"的方法,但它没有调用,并且我收到404错误。我从教程中获取的所有代码,并没有做任何更改。我找不到其他的教程。你能解释一下我做错了什么吗?
GoLang代码:
func main() {
http.Handle("/", http.FileServer(http.Dir("./app/web/")))
fmt.Println("Text")
http.HandleFunc("/api/hello", helloWorld)
http.ListenAndServe(":8080", nil)
}
func helloWorld(w http.ResponseWriter, r *http.Request) {
data := struct {
Message string
}{
"Hello, World",
}
if err := json.NewEncoder(w).Encode(data); err != nil {
log.Println(err)
}
}
Angular Dart代码:
class AppComponent {
Hello hello = new Hello();
}
class Hello{
String message;
Hello(){
HttpRequest.getString('/api/hello')
.then((String content) {
Map parsedMap = JSON.decode(content);
message = parsedMap["Message"];
})
.catchError((Error error) {
print(error.toString());
});
}
}
项目结构:
英文:
I use this tutorial to make a web application with GoLang, Angular2 and Dart, but when i start backend by console command 'backend', and route in browser to "localhost:8080/" it must call method from Dart's class "Hello" but it doesn't call, and i get 404 error. All code i got from tutorial and didn't change anything. And i can't find any other tutorials. Can you explain me what wrong am i doing?
GoLang code:
func main() {
http.Handle("/", http.FileServer(http.Dir("./app/web/")))
fmt.Println("Text")
http.HandleFunc("/api/hello", helloWorld)
http.ListenAndServe(":8080", nil)
}
func helloWorld(w http.ResponseWriter, r *http.Request) {
data := struct {
Message string
}{
"Hello, World",
}
if err := json.NewEncoder(w).Encode(data); err != nil {
log.Println(err)
}
}
and angular dart code:
class AppComponent {
Hello hello = new Hello();
}
class Hello{
String message;
Hello(){
HttpRequest.getString('/api/hello')
.then((String content) {
Map parsedMap = JSON.decode(content);
message = parsedMap["Message"];
})
.catchError((Error error) {
print(error.toString());
});
}
}
答案1
得分: 1
教程已经相当旧了。你需要切换到HashLocationStrategy
(据我所知,那是当时的默认选项)。
请参考 https://angular.io/docs/ts/latest/api/router/HashLocationStrategy-class.html
将
bootstrap(AppComponent);
改为
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
provide(LocationStrategy, {useClass: HashLocationStrategy})
]);
你还需要添加一些额外的导入
import 'package:angular2/router.dart'
show
HashLocationStrategy,
LocationStrategy,
ROUTER_PROVIDERS;
英文:
The tutorial is quite old. You need to switch to HashLocationStrategy
(which was the default back then as far as I know).
See https://angular.io/docs/ts/latest/api/router/HashLocationStrategy-class.html
Change
bootstrap(AppComponent);
to
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
provide(LocationStrategy, {useClass: HashLocationStrategy})
]);
You also need to add some additional imports
import 'package:angular2/router.dart'
show
HashLocationStrategy,
LocationStrategy,
ROUTER_PROVIDERS;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论