客户:
procedure TForm1.Button1Click(Sender: TObject);
begin
gcm := GetGCMInstance;
p := TJavaObjectArray<JString>.Create(1);
p.Items[0] := StringToJString('460004329921');
FRegistrationID := JStringToString(gcm.register(p));
FAlreadyRegistered := (FRegistrationID <> '');
Memo1.Lines.Add(BooltoStr(FAlreadyRegistered));
Memo1.Lines.Add(FRegistrationID);
Memo1.Lines.Add(Edit1.Text);
req.Method := TRESTRequestMethod.rmPOST;
req.AddParameter('tableName', 'users', TRESTRequestParameterKind.pkGETorPOST);
req.AddParameter('regid', FRegistrationID, TRESTRequestParameterKind.pkGETorPOST);
req.AddParameter('email', Edit1.Text, TRESTRequestParameterKind.pkGETorPOST);
req.Execute;
jsonValue:= res.JSONValue;
X := SO(jsonValue.ToString);
Memo1.Lines.Add(X['results'].AsString);
end;
function TForm1.GetGCMInstance: JGoogleCloudMessaging;
begin
result := TJGoogleCloudMessaging.JavaClass.getInstance(SharedActivity.getApplicationContext);
end;
Node.js服务器:
var nodePort = 3030;
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var db = require('mysql');
var dbPool = db.createPool({
host : 'localhost',
user : 'root',
password : '1234',
database : 'test',
port : 3306
});
var gcm = require('node-gcm');
var message = new gcm.Message();
var sender = new gcm.Sender('AIzaSyChp2jTQsgPkLaaVgFh6yoovu1Td7tuQMo'); //Api Key
var registrationIds = [];
registrationIds.push('APA91bGNYh3cIL0jcWAhfTIhTen-ThNQRrSbAJ30UEV7I93ejL0BgWok1VU45xs8p82KKcMj5-7SUXf65UCkNa6rVTJ0nYqwEx0Jv7zezaCvQnrQikKjnJGTXHCQEWXhtTOaeXR__7qQYPV5BudtA_0Thty4itfz5Q');
registrationIds.push('APA91bFQX8NJ4goolOGdA-U_MxtwKLk1wMLYMddXV2FetT4A7z3d_ZPYSRz1lkXWo-6QoYgOR4xYD8WeBwFDGqpuZbiBgYV_1H8JPtdPzKGXRQr5jiMD_C5nntxeWNb0aBIi-ejTGo881S8NWvC4K_u28DlZG47ecQ');
app.use( bodyParser.json() );
app.post('/api/db', function(req, res){
if(!req.body.tableName){
var data = {
ID : req.body.id,
Name : req.body.name
}
tableName = 'person';
}else{
var data = {
email : req.body.email,
regid : req.body.regid
}
tableName = 'users';
}//else
console.log(req.body);
res.setHeader('content-type', 'application/json');
dbPool.getConnection(function(objErr, objConn){
if(objErr){
sendError(res, 503, 'error', 'connection', objErr); //503 - Service Unavailable
}else{
objConn.query("INSERT INTO "+tableName+" SET ? ", data, function(Err, Rows, Fields){
if(Err){
sendError(res, 500, 'error', 'query', Err);
}else{
res.send({
results : 'success'
});
objConn.release();
if(!req.body.tableName){ gcmSend(); }
}//else
});
}//else
});
});
客户端获得了registrationid但是nodejs是console.log(req.body); - &GT; {}(未定义) 我尝试使用get方法,它可以工作但是帖子不起作用。 req.body无法处理变量。
答案 0 :(得分:0)
我忘记解析application/x-www-form-urlencoded
,请在server.js文件中包含以下行并尝试一次。
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));