As the title says... Chat on...

User avatar
By Toshi Bass
#6156 Hi I have a simple script which works fine but I need to send a Access-Control-Allow-Origin: * header to enable CORS so that I can post and get the response via Ajax, am not sure if this can be part of the existing send function or if it needs to be sent prior to that like a pre-header help with this would be appreciated, thanks.

led=0
srv=net.createServer(net.TCP)
srv:listen(8080,function(conn)
conn:on("receive",function(conn,pl)
gpio.mode(3,gpio.OUTPUT)
if string.find(pl,"gpio3=0") then gpio.write(3,0) led=0 end
if string.find(pl,"gpio3=1") then gpio.write(3,1) led=1 end
print(led)
conn:send(led)
conn:on("sent",function(conn) conn:close() end)
end)
end)
User avatar
By jankop
#6174 What should be like this?
...
conn:send('HTTP/1.1 200 OK\r\n\ -- here is HTTP header
Allow-Control-Allow-Origin: *\r\n\ -- here is HTTP header
Content-type: text/html\r\n\r\n\ -- here is HTTP header
<!DOCTYPE HTML>\
<html>\
<head>...</head>\
<title>...</title>\
<body>\
...
</body>\
</html>\
conn:on("sent",function(conn) conn:close() end)
User avatar
By Toshi Bass
#6253 Hi Jankop

Thanks for the inspiration, I have now solved Ajax call with CORS to my esp8266-01

Ajax code
$.ajax({
url: 'http://192.168.0.99:8080',
dataType:'TEXT',
success: function(data){
alert('success')
alert(data) },
error :function() {
alert('something went wrong :-(') },
})
}

ESP8266-01 using0.9.2 nodemcu_512k_20141219

led=0
srv=net.createServer(net.TCP)
srv:listen(8080,function(conn)
conn:on("receive",function(conn,pl)
gpio.mode(3,gpio.OUTPUT)
if string.find(pl,"gpio3=0") then gpio.write(3,0) led=0 end
if string.find(pl,"gpio3=1") then gpio.write(3,1) led=1 end

print('HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin:http://192.168.0.38:8000\r\nAccess-Control-Allow- Methods", "POST, GET\r\nAccess-Control-Allow-Headers *AUTHORISED*\r\nContent-type: text/html\r\nServer: ESP8266-1\r')
print("Send-Responce:",led)

-- CORS Header
conn:send('HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin:http://192.168.0.38:8000\r\nAccess-Control-Allow- Methods", "POST, GET\r\nAccess-Control-Allow-Headers *AUTHORISED*\r\nContent-type: text/html\r\nServer: ESP8266-1\r\n\n')

conn:send(led)
conn:on("sent",function(conn) conn:close() end)
end)
end)

Also tested with Multi_DS18B20 (great script) by Sancho see viewtopic.php?f=19&t=752&start=10#p5992 , I have them working with init.lue to load the script on power up however I have 2 more tasks:

I need to figure out how to load the script on powerup without having to first disconnect gpio3 & gpio4 (for this gpio switcher script)
and how to wake-up the script when its gone to sleep without cycling the power

Any one with any pointers on those 2 point ?

Toshi Bass

(Tools esp8266_flasher , LuaUploader)