POST request on HTML - html

So I tried to make a URL Shrinker for fun and used the Traversy Media tutorial for it.
Here's the GitHub of his project: https://github.com/bradtraversy/url_shortener_service
In order to make it into a full Website, I have to make a UI...
But I am stuck with the POST request I am generating via ejs.
I currently have written this code in my index.ejs:
<body>
<header class="header">
<h1>Shrinker</h1>
</header>
<div class='main'>
<form action="http://localhost:5000/api/url/shorten" method="POST" class="content">
<h2 class="shortenheader">Url Shortener</h2>
<div class="input-group">
<input type="shortUrl" class='neumorph-input' placeholder='Your Link' />
<input type="submit" class='neumorph-btn'>
</div>
</form>
</div>
</body>
But it always gives me the error "Invalid long url" which is coming from the code structure of the file in routes/url.js.
In the tutorial he used a simple POST request with a content-type of application/json. Which worked just fine. I am using mongodb atlas, so the cloud version of the database.
POST http://localhost:5000/api/url/shorten
Content-Type: application/json
{
"longUrl": "https://www.stackoverflow.com"
}
I guess I have to use that type in my index.ejs but I don't know how to do that. Can somebody please help?

Well, a HTML form is sent as an urlencoded string (just like the GET query string) or form-data (which can contain attachments), never JSON. See https://www.w3.org/TR/html401/interact/forms.html#adef-enctype
To achieve that, you will have to make an AJAX request, in which you'll be able to send whatever data you want.
To form the request body you could serialize the form and then convert it to JSON. Or, the easiest way since there's only one property, you could build the body manually: var data=JSON.stringify({longUrl:$("#shortUrl").val()});.
Also, you have an error. type="shortUrl" is not valid. It should be type="text" and name="shortUrl", or id="shortUrl" to be able to select it with $("#shortUrl").
If you've never done it, the easiest way would be with jQuery. See https://api.jquery.com/jquery.ajax/

Related

HTML make h-captcha form required in post form

Hello I am currently trying to implement h-captcha into a html form in my website
However I noticed that by default its not "required" like for example text boxes can made to be
I havent found any good solutions out there who can help me out with this issue
Heres btw how I implement the h-captcha form itself
<form action="/end" method="post">
<button type="submit">Submit</button>
<div class="h-captcha" data-sitekey="sitekey here" data-theme="dark"></div>
<script src="https://js.hcaptcha.com/1/api.js" async defer</script>
</form>
try importing the script in your header.
Even when importing to the head. I also found with my form the same issue. You can leave the hcaptcha and still proceed to submit
If you have a server why not use https://github.com/Realsphere/OpenCAPTCHA
Its free, but only compatible with NodeJS

Convert working form data in POST request to Postman request

I have a working example that sends a request with a HTML form.
<html>
<form action="{{url}}?id=123" method="POST">
<input name="request_token[key]" id="key" />
<button type="submit">go</button>
</form>
</html>
I want to send the same request with Postman, but I don't know how to set the parmeters.
I tried to add "key" with the value in the body in json format (Content-Type was set to application/json). It did not work. And many other variations either.
{
"key": "{{theKey}}"
}
In the network tab, chrome sends request_token[key] as key name. This could not be the one I should send?
How do I convert this example to a working postman request?
I found the solution^^
The key name is "request_token[key]". I was irritated cause I get an error if I want to add brackets in the header. But if I add this key as form-data and not in json format, it works.

How to post metrics to InfluxDB with a simple HTML form?

I'm trying to send a 0 or a 1 to a database within my InfluxDB instance via a POST request from an HTML form. I've done this successfully lots of times through curl, but I can't make it work with a simple HTML form. Consider this HTML code:
<!doctype html>
<!-- this file is called like http://my.influx.server/my_page_name.html -->
<html>
<head>
<title>my simple html/influx sender</title>
<meta charset="UTF-8"/>
</head>
<body>
<form action="http://my.influx.server:8086/write?db=db_name" method="post" enctype="text/plain">
<input name="data" type="hidden" value="my_measurement,tag_name=stuff value=1"/>
<input type="submit" value="insert 1"/>
</form>
<form action="http://my.influx.server:8086/write?db=db_name" method="post" enctype="text/plain">
<input name="data" type="hidden" value="my_measurement,tag_name=stuff value=0"/>
<input type="submit" value="insert 0"/>
</form>
</body>
</html>
The curl command for sending a 1 would be like:
curl -i -XPOST 'http://my.influx.server:8086/write?db=mydb' --data-binary 'my_measurement,tag_name=stuff value=1'
So I tried to make a simple HTML form with just 2 buttons. The code above is the closest I could get to at least try to process the "line interface" syntax, however I'm getting either an error message or just no response and I don't get anything in my InfluxDB. The error message from the code above is:
unable to parse 'data=my_measurement,tag_name=stuff value=1\r': invalid number
If you have a close look at the end of the string, you see a \r that obviously gets added and I suspect that this breaks number parsing (I had something similar some time ago), but at least this seems to try to evaluate the line at all. However, I haven't found a way to remove or avoid the \r. Has someone an idea how to achieve this?
Also, please consider the following additional information:
I want it really simple, just a small HTML file with possibly a bit of JavaScript code, but I'd really like to avoid using PHP, jQuery and such. Also, I'm trying to get used to HTML5 as you might notice, but this shouldn't be the problem.
In this case, I don't need a timestamp for each key press, so instead of passing a timestamp I just use the current time. This is achieved by omitting the timestamp, so the string excluding the \r should be syntactically correct.
I also looked for alternatives, however there was only the idea to use JSON and this seems not to be supported any more due to performance reasons (which I wouldn't expect in my case).
The curl command uses the --data-binary parameter, but it seems I don't have anything like this in HTML. I'm aware of binary enctypes like application/x-binary, but they don't work, because they URL-encode the string and this won't pass the syntax check. The only enctype I found that worked at least close enough is text/plain.
I'm also aware of form data not being sent, if the corresponding <input> element has no name attribute. Then I noticed that the curl string was built like my_measurement,tag_name=stuff value=1, possibly multiple such lines separated by \n, which is not like POST key-value-pairs as in a=1&b=2 (i. e. there is no key, that would be the name attribute). Trying to trick it with name="my_measurement,tag_name" and value="stuff value=1" (which would resemble the original string) was not successful and I still couldn't figure out, which key is expected. I tried with content, query etc. and ended up using data. I kept this then because in the docs they talk about "data" and none of the keys made any difference, as long as one is provided. I suspect InfluxDB to just use the first POST variable ignoring the name, but I can't find any clear statement on this.
I also tried several invisible <input> types like just hidden or a regular textbox hidden by style. This made no difference. Neither did visible elements.
I also considered using AJAX, but I couldn't find anything useful about binary POSTs without key-value content. I even would cope with a page that only works e. g. for Firefox for now, so I don't need to switch between different AJAX object creation algorithms and such (yes, I know, jQuery helps, but see first point above).
EDIT 1: I tried to reproduce the error with curl:
curl -i -XPOST 'http://my.influx.server:8086/write?db=home' --data-binary 'my_measurement,tag_name=stuff value=1\r'
This led to the error message:
unable to parse 'my_measurement,tag_name=stuff value=1\\r': invalid number
with headers:
HTTP/1.1 400 Bad Request
Content-Type: application/json
Request-Id: ...
X-Influxdb-Build: OSS
X-Influxdb-Error: unable to parse 'my_measurement,tag_name=stuff value=1\r': invalid number
X-Influxdb-Version: 1.7.9
X-Request-Id: ...
Date: ...
Content-Length: 78
I conclude:
\r seems to be differently encoded in the error message (characters \ and r instead of an actual carriage return), but in the header it's only \r, however it doesn't make a difference regarding the parsing error, so this is comparable.
There is obviously no key name involved, so this is still different from my attempt above.
EDIT 2: I found out how to show the request headers from a call to curl. The command is:
curl -v -XPOST 'http://my.influx.server:8086/write?db=db_name' --data-binary 'my_measurement,tag_name=stuff value=1'
The relevant portion of the output of the command is:
> POST /write?db=db_name HTTP/1.1
> Host: my.influx.server:8086
> User-Agent: curl/7.58.0
> Accept: */*
> Content-Length: 37
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 37 out of 37 bytes
< HTTP/1.1 204 No Content
< Content-Type: application/json
< Request-Id: ...
< X-Influxdb-Build: OSS
< X-Influxdb-Version: 1.7.9
< X-Request-Id: ...
< Date: Sat, 25 Jan 2020 10:54:11 GMT
I conclude:
Content type of the request invoked by curl with --binary-data is application/x-www-form-urlencoded.
Unfortunately I couldn't achieve to see the actual request body, so I'll try again with some URL-encoded variants. However, my_measurement,tag_name=stuff value=1 is 37 characters as in the request header, so I assume there is no key name like data involved. Currently, I get the same error message I had before I posted this question: unable to parse 'data=my_measurement%2Ctag_name%3Dstuff+value%3D1': missing fields
The \r is gone, but I still can't send data without a key name and the whole string is invalid due to URL-encoding. How to get rid of the URL-encoding?
Finally, I found a solution with JavaScript that worked. This Mozilla doc page was the key to a POST form without keys. My HTML page now looks like this:
<!doctype html>
<!-- this file is called like http://my.influx.server/my_page_name.html -->
<html>
<head>
<title>my simple html/influx sender</title>
<meta charset="UTF-8"/>
</head>
<body>
<form id="form1">
<button>insert 1</button>
</form>
<form id="form0">
<button>insert 0</button>
</form>
<script>
function sendData(value)
{
const str = "my_measurement,tag_name=stuff value=" + value;
const xhr = new XMLHttpRequest();
xhr.addEventListener("load", function(event) {
alert("Success");
});
xhr.addEventListener("error", function(event) {
alert("Error");
});
xhr.open("POST", "http://my.influx.server:8086/write?db=db_name");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(str);
}
const form0 = document.getElementById("form0");
const form1 = document.getElementById("form1");
form0.addEventListener("submit", function(event) {
event.preventDefault();
sendData(0);
});
form1.addEventListener("submit", function(event) {
event.preventDefault();
sendData(1);
});
</script>
</body>
</html>
Note the stripped-down form definitions: There are no actions, methods or enctypes any more, as they are set via JavaScript. Also, there is no regular submit element, instead it is a regular button, however I don't know if this is needed. I'll investigate that later.
The main part is in the script tag underneath the forms. A function sendData prepares an XMLHttpRequest object for POSTing a prepared string and invokes its send method. This function is used in the submit events of each form. Also, this function registers event handlers for successful and failed requests.
The lines below the sendData function identify the forms and register event listeners on their submit event. Each listener prevents its form from submitting in a regular fashion and invokes the appropriate sendData call instead, which will successfully insert values into InfluxDB.
Be aware, though, there is still no guarantee to detect every error. I tried to insert a string into an integer field, which failed, but I still got the "Success"-alert. I'm going to investigate that later.
So in total, I see this problem as sufficiently resolved for my purposes and I hope this helps anyone stumbling across it.
This was a pretty useful post, I ran into this issue with the Sigfox backend and callbacks.
If you put an & at the end of the URL and use content type text/plain the \r\n issue is solved.

HTML Post Form - How To Add Json Data

First of all, thank you all for your help :) Really appreciate it as I am a total noob.
Second, I am trying to add info to an HTML form:
Email Address &email=x - Used in the request body The email address of the user >filling out the form. While an email is not required, HubSpot will not create a >contact without a valid email address. Please see this page for more details >about how the email address will be validated.
HS Context &hs_context=x - Used in the request body A JSON formatted block >that contains contextual information for the form submission. See the following >entries for descriptions of the included data, and below for the format of this >parameter.
I am totally lost here in terms of where to add these and also how to add the JSON data. Here's what I have so far:
<!DOCTYPE html>
<html>
<body>
<form action="https://forms.hubspot.com/uploads/form/v2/:12345/:1234-432-6575-93456" method="post" enctype="application/x-www-form-urlencoded>
E-mail <br>
<input type="email" name="email">
<input type="submit">
</form>
</body>
</html>
Here's the JSON code that needs to be added: >The hs_context parameter should > contain the following data, formatted in JSON.Please Note All parameters must be >URL encoded before being passed through the API, including the hs_context >parameter.
{
"hutk": "60c2ccdfe4892f0fa0593940b12c11aa",
"ipAddress": "192.168.1.12",
"pageUrl": "http://demo.hubapi.com/contact/",
"pageName": "Contact Us",
"redirectUrl": "http://demo.hubapi.com/thank-you/"
}
I've got this far by myself with Googling but now I am completely lost. Help please? :)
I don't know hubspot but I think you have to send your request using javascript.
In your javascript you can easyly get your form parameters by adding an id to your field and doing like so :
var email = document.getElementById('email');
and send your request like described here :
Sending a JSON to server and retrieving a JSON in return, without JQuery

Ajax and Grails for Dummies

I am a rookie Grails user and I am completely new to AJAX. I am not exactly grasping the concept of AJAX, and the material online is fragmented.
From my understanding, in grails if I wanted to execute a method in one of my controllers when a part of my HTML doc loads I could simply use something along the lines of
<div onload="${remoteFunction(action:"foo", update:"foo"...)}" ...>
How is the response from the call to the hypothetical foo returned and how can I access it in a js function?
Can I return an object from a class I created from my hypothetical foo action?
On the return of the foo action you can put simple html as text or render some objects that can be used in the view.
Here you have all the info about the Controller "render"
http://grails.org/doc/latest/ref/Controllers/render.html
You can have a that will be update with that data and work there with it. Then you can access to the Html and data inside that "foo" div with javascript like you usually do.
For example:
Controller.groovy
// renders text to response
render '<div id="bar" onclick="alert($('bar').val())>some text</div>'
View.gsp
//Makes the call and updates foo
<div onload="${remoteFunction(action:"foo", update:"foo"...)}" ...>
<div id="foo" name="foo"></div>
Output
<div onload="theAjaxJavascriptFunctionThatGrailsWillInject" ...>
<div id="foo" name="foo">
<div id="bar" onclick="alert($('bar').val())">some text</div>
</div>
I you return some object from the Controller.grooy then you have to treat it like this in you View.gsp
//Makes the call and updates foo
<div onload="${remoteFunction(action:"foo", update:"foo"...)}" ...>
<div id="foo" name="foo">
${myObject.theValueIWant}
</div>
I added a javascript alert but you can do it the way you like, there are lots of ways to do it.
Hope it helps :)