Reading simple response from Nodemcu via HTTP request - html

Please help me. I have simple NodeMcu webserver that has a /STATUS capability like this:
curl 192.168.0.200:8080/STATUS
response> Doors are open.
I am trying to read this via HTML request like this:
<script>
function readBody(xhr) {
var data;
if (!xhr.responseType || xhr.responseType === "text") {
data = xhr.responseText;
} else if (xhr.responseType === "document") {
data = xhr.responseXML;
} else {
data = xhr.response;
}
return data;
}
document.getElementById("STATUS").onclick = function () {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
console.log(readBody(xhr));
}
}
xhr.open('GET', 'http://192.168.0.200:8080/STATUS', true);
xhr.send(null);
alert(data);
</script>
What am I doing wrong? I have still answer in console>
net::ERR_INVALID_HTTP_RESPONSE
Thank you very much!!

Related

Delete Objects in Bucket with jQuery

How do i selete an object in a bucket through a jQuery-Call. The following Code shows my example for uploading the file. The goal is to have the deleting in a similar way. Thanks
function uploadFile(node) {
$('#hiddenUploadField').click();
$('#hiddenUploadField').change(function () {
if (this.files.length == 0) return;
var file = this.files[0];
switch (node.type) {
case 'bucket':
var formData = new FormData();
formData.append('fileToUpload', file);
formData.append('bucketKey', node.id);
$.ajax({
url: '/api/forge/oss/objects',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$('#appBuckets').jstree(true).refresh_node(node);
}
});
break;
}
});
}
You could expose the necessary part on the server side (just like it is done for the /api/forge/oss/objects endpoint which uploads a file to a given bucket) which then could be called from the client side in a similar way.
Server side:
router.delete('/buckets/:id', function (req, res) {
var tokenSession = new token(req.session)
var id = req.params.id
var buckets = new forgeSDK.BucketsApi();
buckets.deleteBucket(id, tokenSession.getOAuth(), tokenSession.getCredentials())
.then(function (data) {
res.json({ status: "success" })
})
.catch(function (error) {
res.status(error.statusCode).end(error.statusMessage);
})
})
Client side:
function deleteBucket(id) {
console.log("Delete bucket = " + id);
$.ajax({
url: '/dm/buckets/' + encodeURIComponent(id),
type: 'DELETE'
}).done(function (data) {
console.log(data);
if (data.status === 'success') {
$('#forgeFiles').jstree(true).refresh()
showProgress("Bucket deleted", "success")
}
}).fail(function(err) {
console.log('DELETE /dm/buckets/ call failed\n' + err.statusText);
});
}
Have a look at this sample which has both file upload and bucket deletion implemented: https://github.com/adamenagy/oss.manager-nodejs
Ah great, thank you. And how would you solve it on the server side with C# ? Rigth now the Upload on server-side looks like:
[HttpPost]
[Route("api/forge/oss/objects")]
public async Task<dynamic> UploadObject()
{
// basic input validation
HttpRequest req = HttpContext.Current.Request;
if (string.IsNullOrWhiteSpace(req.Params["bucketKey"]))
throw new System.Exception("BucketKey parameter was not provided.");
if (req.Files.Count != 1)
throw new System.Exception("Missing file to upload");
string bucketKey = req.Params["bucketKey"];
HttpPostedFile file = req.Files[0];
// save the file on the server
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"),
file.FileName);
file.SaveAs(fileSavePath);
// get the bucket...
dynamic oauth = await OAuthController.GetInternalAsync();
ObjectsApi objects = new ObjectsApi();
objects.Configuration.AccessToken = oauth.access_token;
// upload the file/object, which will create a new object
dynamic uploadedObj;
using (StreamReader streamReader = new StreamReader(fileSavePath))
{
uploadedObj = await objects.UploadObjectAsync(bucketKey,file.FileName,
(int)streamReader.BaseStream.Length, streamReader.BaseStream,"application/octet-
stream");
}
// cleanup
File.Delete(fileSavePath);
return uploadedObj;
}

XMLHttpRequest is working with IE11 only when fiddler is running

I am new angular 2.
Currently I am working on application which has Padarn server at backend and HTML5 with Angular2 at front end.
I wanted ship one password protected zip file to backend, to achieve this I have written following code but that is not working with IE 11 (works properly when fiddler is running) . Same code is working with Chrome and Firefox browsers.
private makeFileRequest(url: string, params: Array, files: File) {
return new Promise((resolve, reject) => {
var formData: FormData = new FormData();
formData.append("uploads", files, files.name);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(xhr.response);
} else {
reject(xhr.response);
}
}
}
xhr.open("PUT", url, true, ApplicationObjects.configuration.Username, ApplicationObjects.configuration.Password);
xhr.send(formData);
});
Please help.

Uploading Files in angular 2

I am trying to upload a csv/xlxs file in angular 2 but whenever i submit the file, i get an exception file could not upload. please try again from my backend although it works fine on postman. What could be wrong in my code?
//service
constructor (private authenticate:AuthenticationService) {
this.filetrack = Observable.create(observer => {
this.progressObserver = observer
}).share();
}
SendRequest (url: string, params: string[], files: File[]) {
return Observable.create(observer => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(JSON.parse(xhr.response));
observer.complete();
} else {
observer.error(xhr.response);
}
}
};
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.setRequestHeader('Authorization', 'Bearer ' + this.authenticate.user_token);
xhr.send(formData);
});
}
}
//component
export class FileUploadComponent {
constructor(private service:FileUploadService) {
this.service.filetrack.subscribe(
data => {
console.log('progress = '+data);
});
}
onChange(event) {
console.log('onChange');
let files = event.target.files;
console.log(files);
this.service.SendRequest('http://localhost:8000/register/v1/file/country', [], files).subscribe(() => {
console.log('sent');
});
}
}
You have to set another header to be able to upload a file:
xhr.setRequestHeader("Content-Type", "multipart/form-data");

Returning a json Response from a laravel project "Cannot read Property of Null"

I have here in my php file (laravel ) after i send an email and get a response to the mobile application
$msg ="email sent " ; $erreur=false ;
return response()->json(['Message' => $msg, 'erreur' => $erreur]);
But, When I get a response using this code in my javascript file
sendButton.onload = function(e)
{
Ti.API.debug(this.responseText);
var json = this.responseText;
var response = JSON.parse(json);
if (response.erreur == false)
{
alert("a Password has been send to you email ");
}
else
{
alert(response.Message);
}
};
I get this error
The error is pretty straight forward the response is null
sendButton.onload = function(e)
{
Ti.API.debug(this.responseText);
var json = this.responseText;
var response = JSON.parse(json);
if (response !=null && response.erreur == false)
{
alert("A password has been sent to your email.");
}
else
{
console.log(response); //probably doesnt have Message either
}
};
#MikeMiller
here is my Js code that communicates with my API
loginBtn.addEventListener('click',function(e)
{
if ( email.value!='')
{
try {
loginReq.open("POST","http://192.168.0.105/appcelerator/public/");//my local ip im testing on my computer
var params = {
email:email.value,
};
loginReq.send(params);
}catch (e)
{
alert(e.message);
}
}
else
{
alert("All fields are required");
}
});
now here is my code in my API (php laravel )
public function getPassword(Request $request)
{
$email = $request["email"];
$user = \DB::table('users')
->where('email', $request['email'])
->first();
$email = $user->email;
session()->put('email',$email);
if (!$user)
{
$msg = 'invalid email adresses';
$erreur = true ;
}else
{
Mail::send('emails.test',['password' => $this->generatePass() ],function($message )
{
$message->to(session()->get('email'),'Bonjour')->subject('welcome:');
});
$msg = 'Password has benn send to your email ';
$erreur = false;
}
return response()->json(['Message' => $msg, 'erreur' => $erreur]);
}
when it's executed i get the email in my email adresse but the response as you know is null. that's my problem

share data between 2 different controller with shared service

Hallo i have 2 different controller and i want to share some data from the first to the second.
First Controller:
validationApp.controller('loginCtrl'['auth','resetpass','$scope',function(auth,resetpass,$scope) {
$scope.login = function() {
auth.login($scope);
};
The auth service is:
validationApp.service('auth',function ($http,ipCookie,$rootScope,$state,localStorageService) {
$rootScope.authorized = false;
// function to submit the form after all validation has occurred
this.login = function ($scope) {
var hash1 =CryptoJS.SHA256($scope.password)
var rootElem = {};
var loginRequest = {
username: $scope.username,
hash: hash1.toString(CryptoJS.enc.Hex)
};
rootElem.loginRequest = loginRequest;
var makejson = JSON.stringify(rootElem);
$http({
method: 'PUT',
url: url+'/users/'+ $scope.username +'/login/',
data: makejson,
headers:{'Content-Type':'application/json'}
})
.success(function (data,status){
if (200 == status) {
if((data.loginResponse.roles[0] == "USER") && (data.loginResponse.roles[1] == "ADMIN")){
$rootScope.authorized = true;
$state.go('admin');
}
else {
$rootScope.authorized = true;
$state.go('user');
}
}
})
.error(function(data,status){
if (400 == status) {
$rootScope.authorized = false;
$scope.dataValidationError = true;
$scope.message = data.error.message;
}
else if(401 == status){
$rootScope.authorized = false;
$scope.dataValidationError = true;
$scope.message = data.error.message;
}
else if(500 == status){
$rootScope.authorized = false;
$scope.dataValidationError = true;
$scope.message = data.error.message;
}
})
}
data is the returned JSON from Backend.
I want to share some JSON data for example data.loginResponse.username in the second controller.
The second controller is:
validationApp.controller('Secondcontroller'['auth','$scope','$state',function(auth,$scope){}]);
It's for make welcome {{username}} after login.
If you want to share the data to another controller you could use $rootScope if you only need the username from the first controller like this:
Your first controller:
validationApp.controller('Firstcontroller', function(.....){
$scope.login = function() {
var data = auth.login($scope);
$rootScope.username = data.loginResponse.username;
};
});
Your second controller:
validationApp.controller('Secondcontroller', function(.....){
You could access $rootScope.username inside here...
});