无法将数据从Angular应用程序发布到Play!框架 [英] Unable to POST data from Angular application to Play! Framework
问题描述
我从浏览器调试器中收到以下错误:
I am getting the following error from the browser debugger:
来源 http://localhost:8000 在Access-Control-Allow-Origin标头中找不到.
Origin http://localhost:8000 not found in Access-Control-Allow-Origin header.
但是我已经在我的API的Global.java
文件中设置了标头:
However I have set the header in my Global.java
file in my API:
Global.java
@Override
public Promise<SimpleResult> call(Http.Context ctx) throws java.lang.Throwable {
Promise<SimpleResult> result = this.delegate.call(ctx);
Http.Response response = ctx.response();
response.setHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json");
return result;
}
这是我要访问的API路由.
Here is my the API route I am hitting.
路线
POST /api/users/insertuser @controllers.UserController.insertUser
这是控制器方法:
UserController.java
@BodyParser.Of(BodyParser.Json.class)
public Result insertUser() {
JsonNode json = request().body().asJson();
String email = json.findPath("email").asText();
String username = json.findPath("username").asText();
String password = json.findPath("password").asText();
if(email == null || username == null || password == null) {
return badRequest("Missing parameter[s]");
} else {
User user = new User(username, email, false, password, getDate(), getDate());
repo.insertUser(user);
return getUserByEmail(email);
}
}
这是我从Angular应用程序中调用的API:
Here is my API call from my Angular application:
userapiservice.js
var factory = {};
var baseUrl = 'http://127.0.0.1:9000/api/users/';
factory.insertUser = function (user) {
return $http({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
url: baseUrl + 'insertuser/',
params: { username: user.username, email: user.email, password: user.password }
});
};
是否有我想念/做错的事情?在几个浏览器上进行了试用,停留了大约一个星期,我一直在自学,找到了Play!文档要...好吧.
Is there something I am missing/doing wrong? Tried on a couple of browsers, been stuck on it for about a week now, I've been teaching myself as I go along and I've found the Play! documentation to be... okay.
推荐答案
首先添加飞行前请求
OPTIONS /*all controllers.Application.preflight(all)
public static Result preflight(String all) {
response().setHeader("Access-Control-Allow-Origin", "*");
response().setHeader("Allow", "*");
response().setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS, PATCH");
response().setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent, access_token, mode");
return ok();
}
但请记住
@Override
public Promise<SimpleResult> call(Http.Context ctx) throws java.lang.Throwable {
Promise<SimpleResult> result = this.delegate.call(ctx);
Http.Response response = ctx.response();
response.setHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json");
return result;
}
呼叫在内部服务器错误上不起作用
call doesn't work on internal server error
这篇关于无法将数据从Angular应用程序发布到Play!框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!