ESP32 "ESPAsyncWebServer" PUT Json - json

I have a problem with ESP32 "ESPAsyncWebServer" PUT Json. There is an error in the code. How to fix it?
JavaScript Working:
async function test() {
var val = JSON.stringify({on: ledState});
xmlHttp.open("GET", "/test?json="+val, true);
xmlHttp.send();
}
JavaScript Does not work:
async function led() {
var val = JSON.stringify({on: ledState});
try {
const response = await fetch("/led", {
method: "PUT",
body: val,
headers: {"Content-Type": "text/plain"}
});
} catch (error) {console.log("Request Failed: " + error);}
}
Web Server Working:
server.on("/test", HTTP_GET, [](AsyncWebServerRequest *request){
if (startuart) Serial.println("led");
if (request->hasParam("json")) {
String val = request->getParam("json")->value();
if (startuart) Serial.println(val);
request->send(200, "text/plain", "OK");
} else {
if (startuart) Serial.println("No Json!");
request->send(200, "text/plain", "No Json!\n");
}
});
Web Server Does not work:
server.on("/led", HTTP_PUT, [](AsyncWebServerRequest *request){
if (startuart) Serial.println("led");
if (request->hasParam("body")) {
String val = request->getParam("body")->value().c_str(); // value().c_str();
if (startuart) Serial.println(val);
request->send(200, "text/plain", "OK");
} else {
if (startuart) Serial.println("No Json!");
request->send(200, "text/plain", "No Json!\n");
}
});
*server.on("/led", HTTP_PUT, [](AsyncWebServerRequest request)
It works, but the answer "No Json!" is displayed.

Related

What does the URL argument do in the xhr.open() function?

I am writing some server software, and I have tested it using a very simple HTML file. It doesn't seem to make any difference what the URL argument is when I open a new XMLHttpRequest POST request. Can anyone tell me? Here is the code if it helps:
Browser HTML file:
<!DOCTYPE html>
<html>
<body>
<title>This is a title!</title>
<p id="paragraph">
Hello World!
</p>
<script>
setTimeout(() => {
var http = new XMLHttpRequest();
var jsonToSend = {
"name": "Steve Smith",
"age": 25,
"isMale": true
};
http.open("POST", "", true);
http.setRequestHeader("Content-Type", "application/json");
http.send(JSON.stringify(jsonToSend));
}, 3000);
</script>
</body>
</html>
Server code (node.js)
const http = require("http");
const fs = require("fs");
const port = 80;
http.createServer((request, response) => {
if (request.method == "GET") {
try {
var newUrl = request.url.substring(1);
if (request.url == "/") {
newUrl = "test.html";
}
response.writeHead(200, "OK", {"Content-Type": "text/html"});
response.write(fs.readFileSync(newUrl).toString());
} catch (error) {
response.writeHead(404, "Not Found", {"Content-Type": "text/html"});
response.write("<h1>404 not found</h1>");
}
response.end();
} else if (request.method == "POST") {
var body = "";
request.on("data", (chunk) => {
body += chunk.toString();
});
request.on("end", () => {
console.log(JSON.parse(body));
response.statusCode = 200;
response.end(body);
});
}
console.log(request.method + ":");
console.log(" URL: " + request.url);
console.log(" Status code: " + response.statusCode);
}).listen(port, () => {
console.log("Listening on port " + port);
});
It sets the URL the request is made to.
It only doesn't seem to make a difference because you're written a webserver which doesn't pay attention to the URL for POST requests.

Post form data to server flutter

I have been having a lot of trouble sending a post request to a server. It expects a form data type.
This is the error I get after my input.
`image: [The image must be an image.]}}
Most of my data are strings except for an int and a file Image which is selected from gallery by user.
This is my code:
dart code
if(_image!=null){
setState(() {
_isLoading = true;
});
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var uri = NetworkUtils.host +
AuthUtils.updateSessionRequest;
Map<String, String> data = {"_method": "PATCH",
"first_name": widget.first_name,
"last_name": widget.last_name,
"phone": widget.phone,
"industry":widget.industry,
"country": widget.country,
"state": widget.state,
"fav_quote": widget.fav_quote,
"bio_interest": widget.bio_text,
"terms": "1",
"company": widget.company,
"position": widget.job_position,
"linked_in":widget.linkedin_profile,
"institution": widget.institution,
"degree": widget.degree,
"preference[0]": widget.industry};
String authToken = sharedPreferences.getString("token");
try {
final response = await http.post(
uri,
body: data,
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + authToken,
},
);
final responseJson = json.decode(response.body);
print(responseJson.toString());
if (response.statusCode == 200 || response.statusCode == 201) {
//upload image to server after success response
uploadImage(_image);
NetworkUtils.showToast("Profile successfully update!");
});
} else{
setState(() {
_isLoading = false;
});
NetworkUtils.showSnackBar(_scaffoldKey, 'An error occurred. Please try again');
}
return responseJson;
} catch (exception) {
print(exception.toString());
setState(() {
_isLoading = false;
});
NetworkUtils.showSnackBar(_scaffoldKey, 'An error occurred. Please try again');
}
}
uploadImage(File image) async{
var request = http.MultipartRequest(
"POST",
Uri.parse(NetworkUtils.host +
AuthUtils.endPointUpdateProfile));
request.files.add(await http.MultipartFile.fromPath(
'image',
image.path,
));
try {
var streamedResponse = await request.send();
var response = http.Response.fromStream(streamedResponse);
return response;
} catch (e) {
rethrow;
}
}
}
You need to pass your image like this
request.files.add(await http.MultipartFile.fromPath(
'image',
_image,
));
Here an example how to pass File and String using http
var request = http.MultipartRequest(
"POST",
Uri.parse("http://....."));
request.fields['first_name'] = widget.first_name;
request.fields['last_name'] = widget.last_name;
.....
request.files.add(await http.MultipartFile.fromPath(
'image',
path,
));
try {
var streamedResponse = await request.send();
var response = http.Response.fromStream(streamedResponse);
return response;
} catch (e) {
rethrow;
}
From the above only, with a little modification
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void executePostMethod(String title) async {
var request = http.MultipartRequest("POST", Uri.parse("https://localhost:44377/API/GetStateList"));
request.fields['CountryID'] = "1";
// .....
//request.files.add(await http.MultipartFile.fromPath('image',path,)
//);
// send request to upload image
await request.send().then((response) async {
//print(response);
response.stream.transform(utf8.decoder).listen((value) async {
print(value);
// print("ResponseVal: $value");
if (response.statusCode == 200) {
var imgUploadData = json.decode(value);
print(imgUploadData);
} else {
throw Exception("Faild to Load!");
}
});
}).catchError((e) {
print(e);
});
}

reCAPTCHA ajax verification ReferenceError: success is not defined

I am getting an error when I post my ajax call to the reCAPTCHA verification API. I get a "ReferenceError: success is not defined" error on correct input and "ReferenceError: incorrect is not defined" on incorrect insertion of the CAPTCHA. Here is my code:
$.ajax({
type: 'POST',
contentType: "application/json",
dataType: 'jsonp',
url: "http://www.google.com/recaptcha/api/verify",
data: {
privatekey: 'XXXXXXXXXXXXXXXXX',
remoteip: document.getElementById("ipaddress").innerHTML,
challenge: Recaptcha.get_challenge(),
response: Recaptcha.get_response()
},
async: false,
success: function (resp) {
if (resp == "false") {
alert('Please enter captcha words correctly');
reloadRecaptcha();
}
else {
alert('Yeah');
}
}
});
Well I solved my own problem by sending the post data to the page controller.
JS:
$.ajax({
type: 'GET',
contentType: "application/json",
url: "/Register/veriCAPTCHA",
data: {
privateKey: 'XXXXXXXXXXXXXXXX',
remoteip: document.getElementById("ipaddress").innerHTML,
challenge: Recaptcha.get_challenge(),
response: Recaptcha.get_response()
},
success: function (data) {
if (data == false) {
valiCAPTCHA = false;
ALERT("The CAPTCHA code you entered is invalid. Please try again.");
Recaptcha.reload();
}
else {
valiCAPTCHA = true;
}
}
});
CS controller:
[HttpGet]
public JsonResult veriCAPTCHA(string privateKey, string remoteip, string challenge, string response)
{
string postData = String.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}",
privateKey, remoteip,
challenge, response);
JsonResult result = new JsonResult();
byte[] postDataBuffer = System.Text.Encoding.ASCII.GetBytes(postData);
Uri serviceUri = new Uri("http://api-verify.recaptcha.net/verify", UriKind.Absolute);
try
{
HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create(serviceUri);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postDataBuffer.Length;
webRequest.Method = "POST";
//incase you are using a proxy server
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
webRequest.Proxy = proxy;
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(postDataBuffer, 0, postDataBuffer.Length);
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
string jsonResponse = string.Empty;
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
jsonResponse = sr.ReadToEnd();
string[] tokens = jsonResponse.Split(new char[] { '\n' });
if (tokens.Length == 2)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
else
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}

WP8 upload image on server using multipart/form-data, getting error

Following code tries to upload image to server using multipart/form-data:
public async void PostRequest(Stream photoStream, string lomail, string fileName)
{
try
{
using (HttpClient client = new HttpClient())
{
client.Timeout = TimeSpan.FromMinutes(10);
photoStream.Position = 0;
using (MultipartFormDataContent content = new MultipartFormDataContent())
{
content.Add(new StringContent(lomail), "lomail");
content.Add(new StreamContent(photoStream), "photo", fileName);
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("post");
});
HttpResponseMessage response = await client.PostAsync(LoUrl, content);
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(response.ToString());
});
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("finish");
});
}
}
}
catch (Exception e)
{
MessageBox.Show("post request: " + e.Message);
}
}
But there's HTTP error: (status code 404, Http.StramContent, Header: Content-length=0)
How do this correctly?
I found the solution.
public async void PostRequest(Stream photoStream, string lomail, string fileName)
{
try
{
using (HttpClient client = new HttpClient())
{
client.Timeout = TimeSpan.FromMinutes(10);
photoStream.Position = 0;
using (MultipartFormDataContent content = new MultipartFormDataContent())
{
content.Add(new StringContent(lomail), "lomail");
content.Add(new StreamContent(photoStream), "photo", fileName);
//var imageContent = new ByteArrayContent(ImageData);
//imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
//content.Add(imageContent, "photo", "image.jpg");
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("post");
});
HttpResponseMessage response = await client.PostAsync(LoUrl, content);
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(response.ToString());
});
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("finish");
});
}
}
}
catch (Exception e)
{
MessageBox.Show("post request: " + e.Message);
}
}

AngularJS http.get verify valid json

When getting a json from a URL I only want to work with it, when the data is valid.
my approach so far by using JSON:
$http.get(
'data/mydata.json'
+ "?rand=" + Math.random() * 10000,
{cache: false}
)
.then(function (result) {
try {
var jsonObject = JSON.parse(JSON.stringify(result.data)); // verify that json is valid
console.log(jsonObject)
}
catch (e) {
console.log(e) // gets called when parse didn't work
}
})
However before I can do the parsing, angular already fails itself
SyntaxError: Unexpected token {
at Object.parse (native)
at fromJson (http://code.angularjs.org/1.2.0-rc.2/angular.js:908:14)
at $HttpProvider.defaults.defaults.transformResponse (http://code.angularjs.org/1.2.0-rc.2/angular.js:5735:18)
at http://code.angularjs.org/1.2.0-rc.2/angular.js:5710:12
at Array.forEach (native)
at forEach (http://code.angularjs.org/1.2.0-rc.2/angular.js:224:11)
at transformData (http://code.angularjs.org/1.2.0-rc.2/angular.js:5709:3)
at transformResponse (http://code.angularjs.org/1.2.0-rc.2/angular.js:6328:17)
at wrappedCallback (http://code.angularjs.org/1.2.0-rc.2/angular.js:9106:81)
at http://code.angularjs.org/1.2.0-rc.2/angular.js:9192:26 angular.js:7861
How can I prevent angular from throwing this error or how else should I handle verifying the JSON ?
UPDATE: Solution:
$http.get(
// url:
'data/mydata.json'
+ "?rand=" + Math.random() * 10000
,
// config:
{
cache: false,
transformResponse: function (data, headersGetter) {
try {
var jsonObject = JSON.parse(data); // verify that json is valid
return jsonObject;
}
catch (e) {
console.log("did not receive a valid Json: " + e)
}
return {};
}
}
)
You can override transformResponse in $http. Check this other answer.
I was looking for the same thing, and transformResponse does the job, BUT, I dont like using transformResponse everytime i use $http.get() or even overriding it because some $http.get() will be json and some not.
So, here is my solution:
myApp.factory('httpHandler', function($http, $q) {
function createValidJsonRequest(httpRequest) {
return {
errorMessage: function (errorMessage) {
var deferred = $q.defer();
httpRequest
.success(function (response) {
if (response != undefined && typeof response == "object"){
deferred.resolve(response);
} else {
alert(errorMessage + ": Result is not JSON type");
}
})
.error(function(data) {
deferred.reject(data);
alert(errorMessage + ": Server Error");
});
return deferred.promise;
}
};
}
return {
getJSON: function() {
return createValidJsonRequest($http.get.apply(null, arguments));
},
postJSON: function() {
return createValidJsonRequest($http.post.apply(null, arguments));
}
}
});
myApp.controller('MainCtrl', function($scope, httpHandler) {
// Option 1
httpHandler.getJSON(URL_USERS)
.errorMessage("MainCtrl -> Users")
.then(function(response) {
$scope.users = response.users;
});
// Option 2 with catch
httpHandler.getJSON(URL_NEWS)
.errorMessage("MainCtrl -> News")
.then(function(response) {
$scope.news = response.news;
})
.catch(function(result){
// do something in case of error
});
// Option 3 with POST and data
httpHandler.postJSON(URL_SAVE_NEWS, { ... })
.errorMessage("MainCtrl -> addNews")
.then(function(response) {
$scope.news.push(response.new);
});
});