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

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

问题描述

我有一个项目需要使用 Angular2(最终版)发布到旧的、遗留的 Tomcat 7 服务器,该服务器使用 .jsp 页面提供有点 REST 风格的 API.

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.

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

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.

这是从我的 user.service.ts 中截取的:

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.

有没有其他人遇到过这种情况?您如何使用 request.getParameter("param") 强制 Angular2 以可以由旧 Java API 读取的格式发布数据?

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.

推荐答案

2020 年 6 月更新:此答案已有 4 年历史,由于 Angular 中的 API 更改而不再有效.请参阅有关当前版本方法的最新答案.

您可以使用 URLSearchParams 作为请求的主体来执行此操作,Angular 会自动将内容类型设置为 application/x-www-form-urlencoded 并编码身体正常.

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天全站免登陆