我试图使用插件发出一个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说:
{名称:'Test'}
服务器接收的内容:
=%7B%22 22name%22%3A%22测试%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();
}
}发布于 2017-07-15 00:16:57
问题似乎是在本地插件中,所以我改变了角度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';AuthProvider:
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';发布于 2017-07-14 04:15:01
你能不能试着把身体送出去而不把它做成绳子。您可以发送JSON对象而不需要字符串化。试试看:)
**发送后更新
{name: 'Test'}如果你得到了name = "test"
你为什么不试试像这样
var data = JSON.stringify(data);
var obj = {data:data};
//send the obj Object因此它将显示为data = "{name:test}“
现在将其从服务器上解析。试着告诉我:)
发布于 2017-07-14 06:07:00
如果您试图使用HTTP发出post请求,那么尝试以这种格式发送请求。
let body = new FormData(); body.append('name', 'Test'); this.http.post(<url>,body);
试着让我知道它是否适合你。
https://stackoverflow.com/questions/45094411
复制相似问题