HTTP 原生插件 (IONIC 3)

HTTP Native Plugin (IONIC 3)

我正在尝试使用 HTTP cordova 插件发出 post 请求。但是,由于某种原因,服务器端使用的 JSON 数据格式不正确(json brakets)。有人可以帮帮我吗?

进口:

import { HTTP } from '@ionic-native/http';

请求实现:

public sendData(sufix, json) {

    return new Promise((resolve, reject) => {

        this.http.post(URL+sufix, JSON.stringify(json), {'Content-Type': 'application/json'}).then(result => {
            resolve(result.data);
        }).catch(error => {
            reject(error);
        });

    });
}

json发送:

{name: 'Test'}

服务器收到的内容:

=%7B%22name%22%3A%22Test%22%7D

服务器实现:

@Path("/register")
public class RegisterEndPoint {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response registerUser(UserDTO userDTO) {

        // Create DAO for persistence
        FactoryDAO factory = new FactoryDAO();
        UserDAO userDAO = factory.getUserDAO();

        // Create user to be persisted
        if (!userDAO.userExist(userDTO.getEmail())) {

            User user = new User();
            user.setPassword(userDTO.getPassword());
            user.setEmail(userDTO.getEmail());
            user.setName(userDTO.getName());
            userDAO.persist(user);
            userDAO.commit();
            return Response.status(200).build();

        }
        return Response.status(405).entity(new ErrorDTO("User already registered!")).build();

    }


}

能否尝试发送正文而不将其设为字符串。您可以在不进行字符串化的情况下发送 JSON 对象。试一试:)

**更新 发送后

{name: 'Test'}

如果你得到 name = "test"

你为什么不这样试试

var data =  JSON.stringify(data);
var obj = {data:data};
//send the obj Object

所以它会显示为 data = "{name:test}"

现在从服务器解析它。试着让我知道:)

如果您尝试使用 HTTP 发出 post 请求,请尝试以这种格式发送请求。

let body = new FormData(); body.append('name', 'Test'); this.http.post(<url>,body);

试试看是否适合你。

问题好像出在Native Plugin,所以我换成angular http方案,没问题。按照下面我执行的解决方案进行操作。感谢所有帮助过我的人。

需要导入:

import { Http, Headers, RequestOptions, Response } from  '@angular/http';
import { Observable } from 'rxjs/Rx'
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/timeout';

授权提供者:

public sendRequest(sufix, json) {

    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.post(URL+sufix, json, options)
        .timeout(TIMEOUT_REQUEST*1000)
        .do(this.logResponse)
        .map(this.extractData)
        .catch(this.handleError)

}

private logResponse(res: Response) {
    console.log(res);
}

private extractData(res: Response) {
    return res.json();
}

private handleError(res: Response | any) {
    return Observable.throw(res.json().error || 'Fail to connect to the server');
}

调用 AuthProvider:

this.authProvider.sendRequest('register', this.signup).subscribe((data) => {
    console.log('Success!');
}, (error) => {
    console.log(error);
});

供应商包含在 app.module.ts

import { HttpModule, JsonpModule } from '@angular/http';

只需在 post

之前添加 this.http.setDataSerializer(‘json’)