无法将数据从Angular应用程序发布到Play!框架

时间:2015-08-05 22:57:27

标签: javascript java json angularjs playframework

我从浏览器调试器收到以下错误:

  

在Access-Control-Allow-Origin标头中找不到原点http://localhost:8000

但我在我的API中的Global.java文件中设置标题:

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路线。

路由

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调用:

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!文件......好吧。

1 个答案:

答案 0 :(得分:1)

首先添加预检请求

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;
    }

呼叫不会解决内部服务器错误