获取并将数据发布到休息微服务

时间:2017-12-04 12:28:56

标签: angular spring-boot

我正在尝试使用我的Rest微服务创建HTTP服务GET和POST。

我可以从我的Rest微服务中获取数据。

但我无法发出POST请求。

下面显示的是我的Rest微服务代码

WebController.java

package com.central.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.central.model.Users;
import com.central.repository.UsersRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
public class WebController {
    private static final String NULL = null;
    @Autowired
    UsersRepository userRepo;

    @CrossOrigin(origins = "http://localhost:4200")
    @RequestMapping("/checkUsers")
    public String checkLogin() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        List<Users> useObj = (List<Users>) userRepo.findAll();
        return (mapper.writeValueAsString(useObj));
    }

    @CrossOrigin(origins = "http://localhost:4200")
    @RequestMapping(value = "/checkByCredential", method = RequestMethod.POST)
    public String checkLoginByName(@RequestBody Users user) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Users useObj1 = userRepo.findByUsernameAndPassword(user.username, user.password);
        return (mapper.writeValueAsString(useObj1));
    }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { BasicService } from './basic.service';

@NgModule({
  declarations  : [ AppComponent],
  imports       : [BrowserModule,HttpModule,FormsModule ],
  providers     : [BasicService],
  bootstrap     : [AppComponent]
})

export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { BasicService } from './basic.service';

@Component({
  selector: 'app-root',
  template: `<h1>{{ title }}</h1>
                <div style="margin-left:50px; height: 200px; overflow: auto;"> 
                 <table>
                     <tr><td>Username</td>&emsp;&emsp;<td>Password</td></tr>
                     <tr *ngFor= " let item of data">
                 <td>{{ item.username }}</td>&emsp;&emsp;<td>{{ item.password }}</td>
                 </tr>
                 </table>
                </div>


      <h2>Login</h2>
        <form role="form">
          <div ng-control-group="credentials">
            <label for="username">Username</label>
            <input
              type="text"
              #username
              id="username"
              ng-control="username"
              required>

            <label for="password">Password</label>
            <input
              type="password"
              #password
              id="password"
              ng-control="password"
              required>
          </div>
          <button (click)="checkByCredential(username,password)">Login</button>
        </form>`
})


export class AppComponent {
  title: string;
  data: any;

  constructor(private MyService: BasicService) {
    this.title = "Angular Service";

    this.MyService.GetUsers()
      .subscribe(users => { this.data = users });
  }

  checkByCredential(username: string, password: string) {
    this.MyService.checkByCredential(username, password).subscribe(users => { this.data = users });
  }
}

basic.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class BasicService {
  constructor(private http: Http) { }

  GetUsers() {
    return this.http.get('http://localhost:8080/checkUsers')
      .map(result => result.json());
  }

  checkByCredential(username: string, password: string) {
    const user = { username: username, password: password };
    return this.http
      .post('http://localhost:8080/checkByCredential', user)
      .map(result => result.json());
  }
}

当我通过我的表单提交数据时,我在控制台中收到此错误,如下图所示

enter image description here

enter image description here

但是当我尝试使用用户名和密码发布Post请求时,我的邮递员,我能够获取如下图所示的数据

enter image description here

enter image description here

任何人都可以帮我解决角度2中的帖子请求

在我的框架中更新后更新了屏幕截图 enter image description here enter image description here

2 个答案:

答案 0 :(得分:1)

您从服务中获得了400,因为您并未真正向服务器发送值。

这一行:

<button (click)="checkByCredential(username,password)">Login</button>

是有问题的。这两个变量是模板变量,它指的是实际的输入元素,而不是输入元素的值,所以你需要这样做:

<button (click)="checkByCredential(username.value,password.value)">Login</button>

这应该适用于那一点。虽然我建议转换为反应形式或ngModel作为长期解决方案。

至于调试这个,使用console.log,chrome上的网络选项卡,在这种情况下,甚至服务器框架生成的错误消息都会立即向您显示出现了什么问题。< / p>

这样的事情:

checkByCredential(username: string, password: string) {
    console.log(username, password);
    this.MyService.checkByCredential(username, password).subscribe(users => { this.data = users });
}

会立即告诉您,您没有达到预期的价值。

同样,在Chrome中的网络标签上,您可以查看您发送的实际请求正文,并确保它不会格式错误。

最后,如果你仔细观察400错误,你会回来(顺便说一句,400总是意味着用户输入不好),它有一个特定的错误信息,可能会给你一个关于什么的线索的信息。继续。

您的次要错误是因为您尝试使用ngFor来迭代对象,这是不允许的,您只能将ngFor与数组一起使用。您真正的问题是设计不当,并且您尝试在同一元素中显示主列表和单个详细信息项。您应该重新设计您的页面,以便您的用户&#34;检查用户&#34;和你的用户列表&#34;是不同的显示元素。但是对于测试,您可以像这样登录控制台:

this.MyService.checkByCredential(username, password).subscribe(users => console.log(users));

答案 1 :(得分:-1)

我遇到了同样的问题。该问题是由跨域资源共享(CORS)引起的。我创建了一个代理文件,用于将流量从localhost:4200重定向到我的spring localhost(在您的情况下是localhost:8080)。

在您的情况下,我建议您创建一个proxy.conf.json文件,如下所示:

{
  "/": {
    "target": "http://localhost:8080",
    "secure": false
  }
}

..并将代码中的绝对路径更改为相对路径,例如

return this.http
   .post('http://localhost:8080/checkByCredential', user) 
   .map(result => result.json()
)}

为:

return this.http
   .post('/checkByCredential', user) 
   .map(result => result.json()
)}

您可以使用以下命令运行角度应用程序(已启用代理):

ng serve --proxy-config proxy.conf.json

您的项目结构如下:

Project structure

您的WebController也太复杂了;您正在序列化为JSON,但这不是必需的。

package com.central.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.central.model.Users;
import com.central.repository.UsersRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

    @RestController
    public class WebController {
        private static final String NULL = null;
        @Autowired
        UsersRepository userRepo;

        @CrossOrigin(origins = "http://localhost:4200")
        @GetMapping("/checkUsers")
        public List<Users> checkLogin() {
            return userRepo.findAll();
        }

        @CrossOrigin(origins = "http://localhost:4200")
        @PostMapping(value = "/checkByCredential")
        public Users checkLoginByName(@RequestBody Users user) throws Exception {
            return userRepo.findByUsernameAndPassword(user.username, user.password);
        }
    }

我认为从/向JSON解析会出现问题。

不要忘记删除映射方法!例如,更改此

return this.http
   .post('http://localhost:8080/checkByCredential', user) 
   .map(result => result.json()
)}

到:

return this.http.post('http://localhost:8080/checkByCredential', user)