gpt4 book ai didi

解析 url 期间 Angular Http 失败

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:22:09 26 4
gpt4 key购买 nike

在 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 编写的这是我的代码

组件.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);
}
);
}

服务.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);
}

最佳答案

this.details 不需要字符串化。将 Content-Type header 设置为 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);
}
);
}

关于解析 url 期间 Angular Http 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53740444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com