简体   繁体   English

Angular HTTP 请求错误:“发布有效请求”

[英]Angular HTTP request error: “post valid request”

I am new in angular.我是角度的新手。 I am creating signup functionality, but when I post request It gives me the error: "post valid request".我正在创建注册功能,但是当我发布请求时,它给了我错误:“发布有效请求”。 Can you please check my code and tell me what I am doing wrong.您能否检查我的代码并告诉我我做错了什么。

services服务

import { Injectable, OnInit } from '@angular/core';
        import {HttpModule, Http,Response,Headers, RequestOptions,Request,RequestMethod} from '@angular/http';
        import 'rxjs/add/operator/map';
        import { Observable } from "rxjs/Rx";
        import { User } from './user';
        import { HttpClient,HttpHeaders, HttpRequest } from '@angular/common/http';


        @Injectable({
          providedIn: 'root'
        })
        export class RegisterService implements OnInit {

          posts_Url: string = 'http://localhost:8080/GradeMyDrawings/teacher/register';

            constructor(private http: HttpClient) {

            }

            ngOnInit () {

            }

          registerUser(user:User) {     
             return this.http.post(this.posts_Url, JSON.stringify(user))
              .map((response: Response) => response);           
          }
        }

Signup component注册组件

import {Component, OnInit,Input} from '@angular/core'
        import { CommonService }  from '../../_common/services/common.service';
        import { CommonComponent }  from '../../_common/common.component';
        import { User } from '../../shared/user';
        import { RegisterService } from '../../shared/register.service';
        import { Router, RouterModule } from '@angular/router';
        import {HttpModule, Http,Response,Headers, RequestOptions} from '@angular/http';
        import {HttpClient, HttpErrorResponse} from '@angular/common/http';



        @Component ({
            selector: 'app-login',
            templateUrl: './signup.component.html',
            styleUrls: ['./signup.component.css'],
            providers:[RegisterService]
        })

        export class SignUpComponent  implements OnInit {
         public model:any = [];
            constructor (private _resterservie:RegisterService, private router:Router) {  }    


            ngOnInit () {

            }

            register()
            {
              this._resterservie.registerUser(this.model)
                .subscribe(
                  data => {
                    console.log("Successful");
                  },
                  error=> {
                    console.log("Error");
                  }
                )   
            }


        }

Signup html注册html

              <div class="form-group">
                  <input type="text" name="tTitle" [(ngModel)]="model.tTitle" #tTitle = "ngModel"  placeholder="Teacher Title" class="form-control" id="tTitle" />
              </div>
              <div class="form-group">
                  <label id="tq1"><strong>Q1:</strong>What is your Birth Date</label>
                  <input type="text" name="tans1" [(ngModel)]="model.tans1" #tans1 = "ngModel"  placeholder="Security Q1" class="form-control" id="tans1" />
              </div>
              <div class="form-group">
                  <label id="tq2"><strong>Q2:</strong> What is your favourite Sports:</label>
                  <input type="text" name="tans2" [(ngModel)]="model.tans2" #tans2 = "ngModel"  placeholder="Security Q2" class="form-control" id="tans2" />
              </div>
              <div class="form-group">
                  <label id="tq3"><strong>Q3:</strong> What is your favourite Color:</label>
                  <input type="text" name="tans3" [(ngModel)]="model.tans3" #tans3 = "ngModel"  placeholder="Security Q3" class="form-control" id="tans3" />
              </div>
              <div class="form-group">
                  <select class="form-control" id="tSignUpType" name="tsignUpType" [(ngModel)]="model.tsignUpType" #tsignUpType = "ngModel">
                      <option>ADMIN</option>
                      <option>TEACHER</option>

                  </select>
              </div>
              <div class="form-group">
                  <input type="text" name="Email" [(ngModel)]="model.Email" #Email = "ngModel"  placeholder="Email" class="form-control" id="tSignUpEmail" />
              </div>

              <div class="form-group" style="position:relative">
                  <div id="pas-mismatch" style="color: red; position: absolute; top: -18px;"></div>
                  <input type="password"  name="password" [(ngModel)]="model.password" #password = "ngModel"  placeholder="Password" class="form-control" id="tSignUpPassword" />
              </div>
              <div class="form-group">
                  <input type="password" name="password2" [(ngModel)]="model.password2" #password2 = "ngModel"  placeholder="Retype password" class="form-control" id="tconfirmpassword" />
              </div>
              <div class="form-group">
                  <input type="submit" name="signup_submit" class="btn btn-primary"  value="Sign up" id="SignUpbtn" />
                  <button class="btn btn-primary signIn">Sign In</button>
              </div>
              <div class="alert alert-success successful_alert" style="display:none;">
                  Successfully Created your Account, You can login Now!
              </div>

          </form>

user interface用户界面

export interface User {
                        'tsignUpUserid':string;
                        'tsignUpDisplayName':string;
                        'tschoolid':string;
                        'tschoolName':string;
                        'tschoolAd1':string;
                        'tschoolAd2':string;
                        'tschoolZip':string;
                        'tschoolCity':string;
                        'tschoolState':string;
                        'tTitle':string;
                        'tq1':string;
                        'tq2':string;
                        'tq3':string;
                        'tans1':string;
                        'tans2':string;
                        'tans3':string;
                        'tsignUpType':string;
                        'tsignUpPassword':string;
                        'tSignUpEmail':string;

            }

Looks like you are missing .pipe.看起来您缺少 .pipe。 Update your code as below.更新您的代码如下。

registerUser(user: User): Observable<any> {
    return this.http.post(this.posts_Url, user)
        .pipe(
        map((response: Response) => response)
    );
}

Also note:另请注意:
1. Please check if you really need to stringfy user object. 1. 请检查您是否真的需要字符串化用户对象。 You can directly pass json object if your api accepts it that way.如果您的 api 以这种方式接受它,您可以直接传递 json 对象。 2. You don't need to implement 'OnInit' in service class. 2. 不需要在服务类中实现'OnInit'。

Are you trying to send a json to a server and did you add the header content type?您是否尝试将 json 发送到服务器并添加标题内容类型? the error I think is from the server the server is not accepting the request, but if not please share with us a capture or something about the request, or the console error.我认为错误来自服务器,服务器不接受请求,但如果没有,请与我们分享捕获或有关请求的内容,或控制台错误。

please add headers on your post request请在您的帖子请求中添加headers

 let headers = new Headers({ 'Content-Type': 'application/json' });
 let options = new RequestOptions({ headers: headers });

 return this.http.post(this.posts_Url, JSON.stringify(user),options).map(
   (response: Response) => <any>response.json()
 ); 

ADD Access-Control-Allow-Origin in your server configuration or add the following header in your handler file.在您的服务器配置中添加 Access-Control-Allow-Origin 或在您的处理程序文件中添加以下标头。

This example is for php.此示例适用于 php。


 <?php
 header("Access-Control-Allow-Origin: *");
 header('Content-Type: application/json');
 ?>

This is one of the common problem else comment the error what your are getting from browser console.这是常见问题之一,否则评论您从浏览器控制台获得的错误。

Your registerUser(user: User) method accepts a parameter of type User , but you are providing an array to the http request in your singup component.您的registerUser(user: User)方法接受User类型的参数,但您在 singup 组件中为 http 请求提供了一个数组。 So you need to correct this in your signup component所以你需要在你的注册组件中更正这个

public model: User;

You may initialize at first too你也可以先初始化

public model: User = {};

Try this format试试这个格式

registerUser(user: User): Observable<any> {
    return this.http.post(this.posts_Url, user)
        .pipe(
        map((response: Response) =>{ return response.map(i=> 
       (i), )
       }))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM