我希望我能得到一些帮助。下面是我发布的用于发布电子邮件和密码的代码。它一直看起来很好,直到它到达服务器。服务器将其处理为:
{ '{"email":"email@gmail.com","pin":"1234"}': '' }
我不确定问题出在哪里。我已经尝试发送电子邮件并通过POSTman固定,这没有问题。我甚至包括了POSTman创建的标题(Content-Type:application / x-www-form-urlencoded),以确保我以相同的方式发送所有信息。
这是我的离子代码:
export class LoginPage {
baseURL: string = 'http://localhost:1000/api'
data: any;
constructor(public navCtrl: NavController, public navParams: NavParams, private http: Http) {
}
login(email, pin) {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
let body = JSON.stringify({
email: email,
pin: pin
});
console.log(body); //This looks just like it's supposed to
this.http.post(this.baseURL + '/authenticate', body, options)
.map(res => res.json())
.subscribe(data => {
console.log(this.data);
}, error => {
console.log("Oooops!");
});
};
}
这是我的服务器的代码,以防万一我弄乱了。
// ===========================
// get the packages we need ==
// ===========================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var router = express.Router();
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('./config'); // get our config file
var models = require('./app/models/models');
// =======================
// configuration =========
// =======================
var port = process.env.PORT || 1000;
mongoose.connect(config.database); // connect to database
app.set('secret', config.secret); // secret variable
// use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(bodyParser.json()); // support json encoded bodies
// use morgan to log requests to the console
app.use(morgan('dev'));
// =======================
// routes ================
// =======================
// basic route
app.get('/', function (req, res) {
res.send('Hello! The API is at http://localhost:' + port + '/api');
});
var apiRoutes = express();
// apply the routes to our application with the prefix /api
app.use('/api', apiRoutes);
// API ROUTES -------------------
//===============================
// Log a user into their account.
//===============================
apiRoutes.post('/authenticate', function (req, res) {
console.log(req.body); //here I'm getting: { '{"email":"email@gmail.com","pin":"1234"}': '' }
res.json(req.body);
});
app.listen(port);
console.log('Stuff happens at http://localhost:' + port);
答案 0 :(得分:1)
import { Http, URLSearchParams } from '@angular/http';
//make url params
let body = new URLSearchParams();
body.append('email', 'test@tst.com');
body.append('pin', '123456');
使用URLSearchParams代替身体并检查