如何使用x-www-form-urlencoded强制Angular2进行POST [英] How to force Angular2 to POST using x-www-form-urlencoded

查看:152
本文介绍了如何使用x-www-form-urlencoded强制Angular2进行POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目需要使用Angular2(final)发布到一个旧的,旧的Tomcat 7服务器,使用.jsp页面提供一些REST-ish API。



<当项目只是一个执行AJAX请求的简单JQuery应用程序时,这很好用。但是,项目的范围已经扩大,需要使用更现代的框架进行重写。 Angular2对于这项工作看起来很棒,但有一个例外:它拒绝使用任何选项执行POST请求,但拒绝执行API不提取的表单数据。 API期望所有内容都是urlencoded,依靠Java的 request.getParameter(param)语法来提取单个字段。



这是我的user.service.ts剪切:

  import {Injectable}来自'@ angular / core';来自'@ angular / http'的
import {Headers,Response,Http,RequestOptions};来自'rxjs / Observable'的
import {Observable};
import'rxjs / add / operator / map';

@Injectable()
导出类UserService {
private loggedIn = false;
private loginUrl ='http:// localhost:8080 / mpadmin / api / login.jsp';
private headers = new Headers({'Content-Type':'application / x-www-form-urlencoded'});

构造函数(私有http:Http){}

登录(用户名,密码){
返回this.http.post(this.loginUrl,{'username ':username,'password':password},this.headers)
.map((response:Response)=> {
let user = response.json();
if( user){
localStorage.setItem('currentUser',JSON.stringify(user));
}
}
);
}
}

无论我设置标头内容类型是什么,它总是以非编码形式数据的形式到达。它没有兑现我正在设置的标题。



还有其他人遇到过这个吗?你如何使用 request.getParameter(param)

$强制Angular2以旧的Java API读取的格式发布POST数据b
$ b

编辑:对于将来发现此问题的其他人来说,解决方案实际上非常简单。设置帖子的正文如下:

  let body =`username = $ {username}& password = $ {password }`;`

参见Brad的例子。

解决方案

您可以使用 URLSearchParams 作为请求的正文,而angular会自动将内容类型设置为 application / x-www-form-urlencoded 并正确编码正文。

  let body = new URLSearchParams(); 
body.set('username',username);
body.set('密码',密码);

this.http.post(this.loginUrl,body).map(...);

它目前不适合你的原因是你没有以正确的格式编码正文数据并且你没有正确设置标题选项。



你需要像这样对身体进行编码:

  let body =`username = $ {username}& password = $ {password}`; 

你需要像这样设置标题选项:

  this.http.post(this.loginUrl,body,{headers:headers})。map(...); 


I have a project that needs to use Angular2 (final) to post to an old, legacy Tomcat 7 server providing a somewhat REST-ish API using .jsp pages.

This worked fine when the project was just a simple JQuery app performing AJAX requests. However, the scope of the project has grown such that it will need to be rewritten using a more modern framework. Angular2 looks fantastic for the job, with one exception: It refuses to perform POST requests using anything option but as form-data, which the API doesn't extract. The API expects everything to be urlencoded, relying on Java's request.getParameter("param") syntax to extract individual fields.

This is a snipped from my user.service.ts:

import { Injectable }    from '@angular/core';
import { Headers, Response, Http, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class UserService {
    private loggedIn = false;
    private loginUrl = 'http://localhost:8080/mpadmin/api/login.jsp';
    private headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});

    constructor(private http: Http) {}

    login(username, password) {
        return this.http.post(this.loginUrl, {'username': username, 'password':  password}, this.headers)
            .map((response: Response) => {
                let user = response.json();
                if (user) {
                    localStorage.setItem('currentUser', JSON.stringify(user));
                }
            }
        );
    }
}

No matter what I set the header content type to be, it always ends up arriving as non-encoded form-data. It's not honoring the header I'm setting.

Has anyone else encountered this? How do you go about forcing Angular2 to POST data in a format that can be read by an old Java API using request.getParameter("param")?

Edit: For anyone else who finds this in the future, the solution is actually really simple. Set the body of the post like this:

let body = `username=${username}&password=${password}`;`

See Brad's example below.

解决方案

You can do this using URLSearchParams as the body of the request and angular will automatically set the content type to application/x-www-form-urlencoded and encode the body properly.

let body = new URLSearchParams();
body.set('username', username);
body.set('password', password);

this.http.post(this.loginUrl, body).map(...);

The reason it's not currently working for you is you're not encoding the body data in the correct format and you're not setting the header options correctly.

You need to encode the body like this:

let body = `username=${username}&password=${password}`;

You need to set the header options like this:

this.http.post(this.loginUrl, body, { headers: headers }).map(...);

这篇关于如何使用x-www-form-urlencoded强制Angular2进行POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆