使用angular。中的http.post方法发布表单数据时出现错误。我正在将表单数据成功存储到数据库中,但是http返回如下解析错误:
HttpErrorResponse
error: {error: SyntaxError: Unexpected token I in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttp…, text: "Inserted Successfully"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8080/api/post"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
我不知道问题出在哪里。 API是用Spring Boot编写的 这是我的代码
component.ts
details: UserDetails = {
firstName: '',
lastName: '',
email: '',
adress: '',
city: '',
state: ''
};
public sendDetails(): void {
const url = 'http://localhost:8080/api/post';
const headers = new HttpHeaders().set('Content-Type', 'application/json');
this.http.post(url, JSON.stringify(this.details), {headers : headers} ).subscribe(
data => {
console.log(data);
},
err => {
console.error(err);
}
);
}
Service.java
public String postData(Map map) throws SQLException {
Connection conn = null;
CallableStatement cs = null;
try {
conn = ds.getConnection();
cs = conn.prepareCall("Begin leo_pack.leo_postUserData1(?, ?, ?, ?, ?, ?); End;");
cs.setString(1, String.valueOf(map.get("firstName")));
cs.setString(2, String.valueOf(map.get("lastName")));
cs.setString(3, String.valueOf(map.get("email")));
cs.setString(4, String.valueOf(map.get("adress")));
cs.setString(5, String.valueOf(map.get("city")));
cs.setString(6, String.valueOf(map.get("state")));
cs.execute();
return "Inserted Successfully";
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (cs != null) cs.close();
if (conn != null) ds.evictConnection(conn);
}
return null;
}
Controller.java
@PostMapping(value = "/post", consumes = MediaType.APPLICATION_JSON_VALUE)
private String test(@RequestBody Map map, BindingResult binding) throws SQLException, ValidationException {
if(binding.hasErrors()){
throw new ValidationException("error !!! ");
}
return service.postData(map);
}
答案 0 :(得分:0)
this.details
不需要进行字符串化。同样将Content-Type
标头设置为application/json
是多余的。
尝试一下:
constructor(private http: HttpClient, ...) {}
...
public sendDetails(): void {
const url = 'http://localhost:8080/api/post';
this.http.post(url, this.details).subscribe(
data => {
console.log(data);
},
err => {
console.error(err);
}
);
}