【问题标题】:Can't send values from angular 2 to spring controller using Rest无法使用Rest将角度2的值发送到弹簧控制器
【发布时间】:2017-03-09 16:25:50
【问题描述】:

我正在尝试创建一个 CRUD 应用程序,对于 Select 操作一切正常,但我无法通过将表单的值发送到 spring 控制器来创建新的 Personne 这是我的 app-components.ts

        import { personne } from './personne';
    import { StylesCompileResult } from '@angular/compiler';
    import { Component } from '@angular/core';
    import { Http, Response, Headers, RequestOptions } from '@angular/http';
    import { Observable } from 'rxjs';
    import 'rxjs/add/operator/map';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'ICS DashBoard Project';
      http: Http;
      contacts = [
        'toto',
        'momo',
        'soso'
      ];
      personne: Observable<personne[]>;
      constructor(http: Http) {
        //http.get('http://localhost:8082/personne/all');
        this.http = http;
        this.http.get('http://localhost:8082/personne/all').subscribe((res: Response) => this.personne = res.json());


      }

      addPersonne(nom: string, prenom: string, age: number, dateNaissance) {


        /*
        console.log(nom);
          this.http.post('http://localhost:8086/personne/save', 
              {"prenom": prenom,
              "nom":nom,
              "age":age,
              "dateNaissance":dateNaissance
          }).toPromise(); * 
         */
        /*
            var headers = new Headers({ 'Content-Type': 'application/json' });
            var options = new RequestOptions({ headers: headers });
            var body = JSON.stringify( {
            var1:'test',
            var2:'test2'
            });
            var params='json'+body;
            this.http.post('http://validate.jsontest.com', body, headers).map((res: Response) => res.json());
            console.log("ajoutee");
              */
        // var json=JSON.stringify({var1:'test1',var2:3});
        var params = {

          "prenom": prenom,
          "nom": nom,
          "age": age,
          "dateNaissance": dateNaissance
        }

        let options = new RequestOptions({ headers: headers });
        //var head = new Headers();
        console.log("TOTO");
        // head.append('Content-Type','application/x-www-form-urlencoded');
        /*this.http.post('http://localhost:8082/personne/save',params,{

          headers:head
       }).map(res=> res.json())*/


      var headers = new Headers();
      headers.append('Content-Type', 'application/x-www-form-urlencoded');

      this.http.post('http://localhost:3001/sessions/create', params, {
        headers: headers
        })
        .map(res => res.json())
        .subscribe(


          () => console.log('Authentication Complete')
        );
      }
    /*
    updatePersonne(oldName:string, newName:string){
      console.log("UPDATE");
      this.http.post('http://localhost:8082/personne/update', { "oldName": oldName, "newName": newName });
    }*/
          }

这是我的休息控制器

            package org.sqli.Controller;

        import java.util.List;

        import org.sqli.entities.Personne;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.CrossOrigin;
        import org.springframework.web.bind.annotation.PathVariable;
        import org.springframework.web.bind.annotation.RequestBody;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RequestMethod;
        import org.springframework.web.bind.annotation.RestController;
        import org.sqli.service.PersonneService;

        @RestController
        //@CrossOrigin("*")
        //@CrossOrigin(origins = "http://localhost:4200")
        @RequestMapping(value="/personne")
        public class PersonneRestController {

            @Autowired
            private PersonneService personneService;

            @CrossOrigin
            @RequestMapping(value="/save")
            public Personne savePersonne(@RequestBody Personne p){

                System.out.println("persoone :::"+p.getNom());
                return personneService.savePersonne(p);

            }
        /*  @CrossOrigin
            @RequestMapping(value="/update",method=RequestMethod.POST)
            public Personne updatePersonne(@RequestBody String oldName , String newName){
                List<Personne> lPersonne = listPersonne();
                Personne newPersonne = null;
                for(Personne personne : lPersonne){
                    if(personne.getNom().equals(oldName)){
                        newPersonne = personne;
                        newPersonne.setNom(newName);
                        break;
                    }
                }
                    return personneService.updatePersonne(newPersonne);

            }*/

        /*  @CrossOrigin
            @RequestMapping(value="savep",method=RequestMethod.PUT)
            public Personne savePersonnep(@RequestBody Personne p){

                return personneService.savePersonne(p);
            }*/
            @CrossOrigin
            @RequestMapping(value="/all")
            public List<Personne> listPersonne(){
                return personneService.listPersonne();
            }
            @CrossOrigin
            @RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE)
            public void deletePersonne(@PathVariable Long id){
                System.out.println("Delete bien");
                personneService.deletePersonne(id);

            }




        }

【问题讨论】:

  • 结果如何?错误?它是什么?你做了什么类型的调试?你发现了什么?
  • 我认为内容类型是个问题
  • 所以首先我开始调试,问题是我的休息控制器中的方法 savePersonne 没有执行,当我从浏览器检查网络时,get 操作成功完成,但情况不同post方法,我认为问题出在app-components.ts的post函数中

标签: java angular spring-boot


【解决方案1】:

需要添加请求方法

 @PostMapping(value = "/save", consumes = { MediaType.APPLICATION_JSON_UTF8_VALUE })
public Personne savePersonne(@RequestBody Personne p){

                System.out.println("persoone :::"+p.getNom());
                return personneService.savePersonne(p);

            }

并验证服务的post方法中的url(AppComponent/addpersonne)

【讨论】:

  • 是的,现在 post 操作已成功完成,但我在调试浏览器中遇到此错误 XMLHttpRequest cannot load localhost:8082/personne/save。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'localhost:4200' 不允许访问。响应的 HTTP 状态代码为 415。
  • 我试图消除这条指令 headers.append('Content-Type', 'application/x-www-form-urlencoded');现在可以使用了,非常感谢
  • 真为你高兴!
【解决方案2】:

使用的 url 与控制器的端点不匹配:

 //addPersonne
 this.http.post('http://localhost:port/personne/save', params, {
    headers: headers
    })
    .map(res => res.json())
    .subscribe(


      () => console.log('Authentication Complete')
    );

【讨论】:

    猜你喜欢
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多