Angular 4不支持的媒体类型
因此,在后端,我有dropwizard,我想访问我的/user/register路径 代码:Angular 4不支持的媒体类型,angular,jersey,dropwizard,http-status-code-415,Angular,Jersey,Dropwizard,Http Status Code 415,因此,在后端,我有dropwizard,我想访问我的/user/register路径 代码: 不要设置内容类型标题。不要将字符串化为JSON。只需发送对象,Angular就可以为您完成这两项工作。另外,在ES6/TypeScript中,{name:name,password:password}可以简化为{name,password}。最后,您的then()回调函数将响应的承诺转换为未定义的承诺。您可能不希望这样做。对于记录,您的代码应该是:newrequestoptions({headers:t
不要设置内容类型标题。不要将字符串化为JSON。只需发送对象,Angular就可以为您完成这两项工作。另外,在ES6/TypeScript中,
{name:name,password:password}
可以简化为{name,password}
。最后,您的then()回调函数将响应的承诺转换为未定义的承诺。您可能不希望这样做。对于记录,您的代码应该是:newrequestoptions({headers:this.headers})
@JBNizet返回未定义的承诺是什么意思?register()方法应该返回承诺,但它返回承诺。如果调用方不执行service.register(…)。然后(user->console.log(user))
,将打印undefined。collback应该是response=>response.json()
。好的,明白了。再次非常感谢!不要设置内容类型标题。不要将字符串化为JSON。只需发送对象,Angular就可以为您完成这两项工作。另外,在ES6/TypeScript中,{name:name,password:password}
可以简化为{name,password}
。最后,您的then()回调函数将响应的承诺转换为未定义的承诺。您可能不希望这样做。对于记录,您的代码应该是:newrequestoptions({headers:this.headers})
@JBNizet返回未定义的承诺是什么意思?register()方法应该返回承诺,但它返回承诺。如果调用方不执行service.register(…)。然后(user->console.log(user))
,将打印undefined。collback应该是response=>response.json()
。好的,明白了。再次非常感谢!
@Path("/user/register")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response register(UserRB userRB) {
String salt = BCrypt.gensalt(16);
Response response;
User newUser = new User();
newUser.setName(userRB.getName());
newUser.setMonths(new ArrayList<>());
newUser.setPassword(BCrypt.hashpw(userRB.getPassword(), salt));
newUser.setSalt(salt);
for (User user : Ebean.find(User.class).findList()) {
if (user.getName().equals(newUser.getName())) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
Ebean.save(newUser);
response = Response.ok(newUser).status(Response.Status.CREATED).build();
return response;
}
import { Injectable } from '@angular/core';
import {Http, RequestOptions} from '@angular/http';
import {User} from './user';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class RegisterService {
private headers = new Headers({ 'content-type': 'application/json' });
private options = new RequestOptions(this.headers);
constructor(private http: Http) { }
private handleError(error: any): Promise<any> {
console.error('An error just happened: ', error);
return Promise.reject(error.message || error);
}
register(name: String, password: String): Promise<User> {
return this.http.post('http://localhost:8080/timelogger/user/register',
JSON.stringify( { name: name, password: password } ), this.options)
.toPromise()
.then((response) => console.log(response))
.catch(this.handleError);
}
}
key:"content-type"
value:"Content-Type"