I am getting the following error from the browser debugger:
Origin http://localhost:8000 not found in Access-Control-Allow-Origin header.
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;
}
Here is my the API route I am hitting.
routes
POST /api/users/insertuser @controllers.UserController.insertUser
And here is the controller method:
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);
}
}
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 }
});
};
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.
first add preflight request
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();
}
but remember
@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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.