2016-10-06 32 views
2

我是lua和node js的新手,我試圖將我正在使用的移動應用連接到服務器。問題是它連接到服務器,但我試圖傳遞的數據會丟失,或者它不會到達服務器。 關於我在做什麼錯的任何想法?如何連接我的移動應用程序(用lua編寫)和我的服務器(用node.js編寫)?

this is my lua code to connect to the server

local function store() 

    local headers = {} 

    headers["Content-Type"] = "application/x-www-form-urlencoded" 
    headers["Accept-Language"] = "en-US" 

    local body = "fname="..fname 
    local params = {} 

    params.headers = headers 
    params.body = body 

    print(body) 
    print(headers) 
    print(params.body) 
    print(params.headers) 

    network.request("http://192.168.56.2:8888", "POST", networkListener, params) 

end 



local function networkListener(event) 
     if (event.isError) then 
     print("Network error!") 
    else 
     print ("RESPONSE: " .. event.response) 
     local serializedString = json.decode(event.response) 

          print(serializedString) 

     --data = json.decode(serializedString) 
     --print(serializedString.student[1]) 

    end 
end 

`

This is the code for the simple server I am trying to send a request to

var express = require('express'); 
var app = express(); 

var morgan = require('morgan'); 
var consolidate = require('consolidate'); 
var bodyparser = require('body-parser'); 
var parser = require('luaparse'); 

//////////////////////////////////////////////////////////////////////////////// 

app.listen(8888,function() {console.log('Server Running!');}); 

//////////////////////////////////////////////////////////////////////////////// 

app.set('views', __dirname + '/views'); 
app.engine('html', consolidate.nunjucks); 
app.use(morgan('dev')); 
app.use(bodyparser.urlencoded({ extended: true })); 
app.use('/static', express.static(__dirname + '/static')); 

//////////////////////////////////////////////////////////////////////////////// 

app.get('/', function(req, res) { 
    res.render('index.html'); 
}); 

app.post('/', function(req, res) { 
    var fname = req.fname; 
    var lname = req.body.lastname; 

    console.log("it went in"); 
    console.log(req.body.fname); 
    console.log(req.body); 
    console.log(req.header); 
    console.log("nahuman"); 


    res.render('index.html'); 
}); 

//////////////////////////////////////////////////////////////////////////////// 
+1

如果可能的話,請在圖片鏈接處填入代碼。 – vivek

+0

我編輯了我的問題,幷包含部分代碼 –

回答

1

你的代碼是好的,但它似乎您的網絡監聽networkListener()之後您store()函數聲明。 Lua無法訪問正在執行的內容,,除非它是前向聲明的。所以,lua沒有找到監聽者,即使有錯誤,它也不會被調用。這個功能應該將store()函數前聲明,以便它可以訪問它,就像這樣:

local function networkListener(event) 
    ... 
end 

local function store() 
    ... 
end 

這,或者你可以轉發聲明它,有點像這樣:

local networkListener = nil -- This forward declaration 

local function store() 
    ... 
end 

networkListener = function() 
    ... 
end 

Here is more info about lua forward declaration。我知道這種情況,因爲您向我們提供了您的實際代碼順序的屏幕截圖。嘗試解決方案後,您始終可以使用調試器查看一切正常。我推薦IDE zerobrane studio

+0

非常感謝! :) –

相關問題