所以我想以JSON格式将数据发送到后端。用户必须从数据列表中选择一个选项,然后ID和名称将被发送到REST服务器。当我从数据列表中发送所选选项的ID和名称时,它给我一个错误消息:内部服务器错误500和SyntaxError:JSON.parse:JSON数据第1行第1列中的意外字符。
我编辑了数据,仅通过mozilla调试选项将名称发送到服务器,然后它接受带有201响应的POST请求。当我仅发送ID时,它会给出相同的500个内部服务器错误响应。 为什么当我发送名字时只接受它?如何更改它,以使Get请求显示一个ID和一个名称?
我将Angular 7用于前端,将glassfish REST服务器用于后端。我希望有一个人可以帮助我。 我在JSON检查器中检查了JSON格式,并通过了测试。我将在评论中提供一些照片,向您展示我的意思。
以下是我要发送的示例:
{"id":3,"name":"Burger King"}
仅接受的内容:
{"name":"Burger King"}
前锋
HTML文件:
<label for="codes">Choose a restaurant:</label>
<form
(ngSubmit)="onOrganize(f)"
#f="ngForm">
<input type="text" list="codes" [(ngModel)]=codeValue [ngModelOptions]="{standalone: true}" (change)="saveCode($event)">
<datalist id="codes">
<option *ngFor="let c of codeList" [value]="c.name" >{{c.name}}</option>
</datalist>
</form>
打字稿文件:
export class OrganizeComponent implements OnInit {
public codeValue: string;
codeList = [
{ restaurantId: 1, name: 'Mcdonalds' },
{ restaurantId: 2, name: 'Kentucky Fried Chicken' },
{ restaurantId: 3, name: 'Burger King' },
{ restaurantId: 4, name: 'Dominos pizza' },
{ restaurantId: 5, name: 'New York Pizza' }
];
@ViewChild('f') form: NgForm;
restaurant = {
restaurantId: 1,
name: " "
};
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
constructor(private http: HttpClient) {
}
ngOnInit() {
}
public saveCode(e): void {
let name = e.target.value;
let list = this.codeList.filter(x => x.name === name)[0];
this.restaurant.restaurantId = list.restaurantId;
this.restaurant.name = list.name;
console.log(list.restaurantId);
console.log(list.name);
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
const data = {
id: list.restaurantId,
name: list.name
};
console.log(data)
var yourDataStr = JSON.stringify(data)
this.http.post('http://localhost:8080/aquadine-jee/resources/restaurant',
JSON.parse(JSON.stringify(data)) , httpOptions)
.subscribe( // subscribe to observable http.post
res => {
console.log("response" + " " + res); // log results otherwise log error
},
err => {
console.log('Error occured');
}
);
}
BACKEND
餐厅文件:
@Entity
@NamedQueries({
@NamedQuery(name = "Restaurant.findOne", query = "select m from Restaurant m where m.id = :id"),
@NamedQuery(name = "Restaurant.getAll", query = "select m from Restaurant m")
})
public class Restaurant {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
// @NotBlank
private String naam;
// @NotBlank
private String adres;
private int restaurantId;
public Restaurant(){
}
public Restaurant( int id, int restaurantId, String naam) {
this.id = id;
this.restaurantId = restaurantId;
this.naam = naam;
}
@GET
@Produces("application/json")
public Response all(){
List<Restaurant> all = repositoryService.getAllRestaurants();
return Response
.status(200)
.header("Access-Control-Allow-Origin", "*")
.entity(all)
.build();
}
@POST
@Consumes("application/json")
public Response save(Restaurant restaurant){
repositoryService.save(restaurant);
return Response
.status(201)
.build();
}
存储库文件
// Restaurant services
public List<Restaurant> getAllRestaurants(){
return entityManager.createNamedQuery("Restaurant.getAll", Restaurant.class).getResultList();
}
public Restaurant find(Integer id){
return entityManager.createNamedQuery("Restaurant.findOne", Restaurant.class).setParameter("id", id).getSingleResult();
}
public void save(Restaurant restaurant){
entityManager.persist(restaurant);
}
public void update(Restaurant restaurant){
entityManager.merge(restaurant);
}
public void delete(Restaurant restaurant){
entityManager.remove(restaurant);
}
答案 0 :(得分:0)
当您在后端使用Modal类接收时,发送的数据应映射到模型类。例如:
后端命名转换应与接收数据相同
您正在发送
{"id":3,"name":"Burger King"}
这样的模型类
映射模型类
class Restaurant{
Integer id;
String name; // your variable name is naam, so it won't map
//Getters and setters
//constructor -- You should have argument constructor
}
您正在发送name
,但是模型类naam
中存在拼写错误