以角度发送数据

时间:2019-05-24 17:11:09

标签: angular

问题是什么,当我尝试从前端向后端发送dato时出现错误400,我不明白是什么问题。

import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http';


@Injectable({
    providedIn: 'root'
})
export class ListUserService {

    constructor(public http: HttpClient) {
        this.http.get(`http://localhost:8080/user/getUsers/`)
            .subscribe(response => {
                console.log(response);
            });
    }

addFriend(user) {
        const config = new HttpHeaders().set('Content-Type', 'application/json').set('Accept', 'application/json')
        const url = 'http://localhost:8080/meet/friend?idOwner=?&idUser=?';
        console.log('SS', user.id);
        const body = JSON.stringify({"idOwner": 89.9, "idUser": 89.9});

        return this.http.post(url, body, {headers: config}).subscribe(response => {
            console.log('jkljl', response);
        });
    }
    }

这是spring -java中的要点,端点需要两个参数,一个id-Owner和id-User

   @RequestMapping(
            value = "/friend/{idUser}/owner/{idOwner}",
            method = RequestMethod.POST
    )
    public ResponseEntity<Meet> friend(  @PathVariable Long idUser,@PathVariable Long idOwner) {
        log.info("PUSEN " +idOwner+"   "+idUser);
        return new ResponseEntity<Meet>(meetService.createMeetWithFriend(idOwner, idUser), HttpStatus.OK);
    }

我收到此错误:

019-05-24 14:30:18.518  WARN 9840 --- [nio-8080-exec-2] o.s.web.servlet.PageNotFound             : No mapping found for HTTP request with URI [/meet/friend] in DispatcherServlet with name
'dispatcherServlet'

1 个答案:

答案 0 :(得分:1)

在向Spring Boot应用程序发布帖子时,需要在Spring Rest Controller中进行一些调整。

@RequestParam用于从URL获取查询参数,例如:见面/朋友? idOwner = 1&idUser = 2,这不是您的情况。您需要以RequestBody身份接收。

我建议您创建一个简单的Java Pojo类,其中仅包含您打算接收的字段,例如:

public class Friend {
    public Long id1;
    public Long id2;

   // Getters and Setters
}

然后,您在Java控制器中更改方法以接收此新类,例如:

public ResponseEntity<Meet> friend(@RequestBody Friend friend) {
    // Log what you need here
    return new ResponseEntity<Meet>(meetService.createMeetWithFriend(friend.getId1(), friend.getId2()), HttpStatus.OK);
}

请注意pojo类的属性名称,该属性必须与您是Stringfy的json属性名称相匹配。