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.
Related
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/
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.
I'm actually working on a website that I have very little control over.
I have a form with a Drop down menu implemented like in the following code
<form method="GET" action="/particulier/fichePays">
<select id="pays">
<option value="1">Spain</option>
<option value="2">France</option>
<option value="3">USA</option>
</select>
<button type='submit' class='btn btn-default'>Valider</button>
</form>
The problem here is, when I click on the submit button, the value of the selected option is automatically added at end of the resulted URL. For example, if i select France, the resulted url is
/particulier/fichePays?pays=2
Instaed of
/particulier/fichePays
I don't have a great control on the website, so for some reason, I cannot remove the id=pays in the select declaration.
Is there any way to remove the automatically added ?pays=valueSelected at the end of the URL please?
Do you have control over the method?
If yes you could use POST instead of GET.
The difference according to this link is:
GET Method:
Appends form-data into the URL in name/value pairs
The length of a URL is limited (about 3000 characters)
Never use GET to send sensitive data! (will be visible in the URL)
Useful for form submissions where a user wants to bookmark the result
GET is better for non-secure data, like query strings in Google
POST Method:
Appends form-data inside the body of the HTTP request (data is not shown is in URL)
Has no size limitations
Form submissions with POST cannot be bookmarked
Hope this helps.
use post method instead of get method
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
I understand how to pull out the data attribute in JQuery from an HTML form, but can it be done from within a .cfc controller to which a form is passed?
Page.cfm
<cfform action="controller.cfc" method="getData">
<cfinput name="uploadMyData" type="submit" data-primaryID="123">
</cfform>
Controller.cfc
function getData(rc){
writeDump(rc.uploadMyData.?????(primaryId)????);
}
Not sure if the data attribute is stored in any way in the struct.
I tried a getMetaData on the rc.uploadMyData but just got a list of java functions.
Update
Adrian J. Moreno
Data attributes are just markup that impact the internal data object of the element. They are not part of a form request. You wouldn't submit a form to a CFC file either. Using Ajax, you can read the value from the data attribute and pass it to the server as part of the request's data packet.
So in Page.cfm
<script type="text/javascript">
var otherData = $("#myForm").serialize();
function sendForm(){
var primaryID = $("#submitData").data("primaryID");
jQuery.post("urlpath/controller/",'{"id":'+''+primaryID+'}', function(dataReturn, status){
//I want to get my form and submit the other data as well to the controller
}
}
</script>
<form id="myForm" action="sendForm()">
<input name="uploadMyData" id="submitData" type="submit" data-primaryID="123">
<input name="importantThing" value="#importantVariable#" type="text">
</form>
pass it to the server as part of the request's data packet.
how would I pass them together?
I want this form submission to redirect to another page so I don't see how I couldn't use the controller? The form data should go the newPage.cfc to process it and get it ready for output on newPage.cfm. I'm using framework one but that doesn't change much.
Thanks for the help, what do you think?
Update 2
Ok, now I ask myself why I would want to submit a form with both ajax and coldfusion form submission together? I realize that's not what should be done. I can either
Submit the form via JQuery/Ajax with no page reload, and include the data attribute in the post url and include the serialized form data
Page.cfm
<script type="text/javascript">
var otherData = $("#myForm").serialize();
function sendForm(){
var primaryID = $("#submitData").data("primaryID");
jQuery.post("controller/method/?primaryId="+primaryID+"",otherData, function(dataReturn, status){
//do stuff with dataReturn or do a javascript redirect
}
}
</script>
Controller.cfc
function method(requestContext){
//do stuff with that otherData, all stored in request context. includes the primaryID value i appended to the url
//send it back to the Page.cfm
fw.renderData("rawjson",jsonString,200,"");
}
and if that made it back ok, I could run a function back in my original view with that information. Like display it on the page.
Submit the form traditionally which would result in a page reload. Include a hidden input type with the value that I want to pass.
Page.cfm
<cfform action="controller.method" method="getData">
<cfinput name="uploadMyData" type="submit" value="Submit Form Button">
<cfinput name="primaryID" type="hidden" value="123">
</cfform>
Controller.cfc
function method(requestContext){
//do stuff with requestContext.primaryID
//go to the view method.cfm or do a fw.redirect("new page or back to the page i came from");
}
Why would we want to submit the form twice? just do one or the other.
Matt, I think you're confused about a number of things that are quite basic to HTML, JavaScript and jQuery and have nothing to do with ColdFusion.
Let's start with an HTML Form.
<form id="{{unique_dom_value}}" action="{{uri}}" method="{{http_verb}}">
unique_dom_value: Some string unique to the document. Allows you to reference the entire form object using JavaScript.
uri: The URI to which you submit the form for processing.
http_verb: Defaults to GET, but you should most often use POST.
The URI you're trying to post to in just controller.cfc, but that won't do anything but redirect you to the ColdFusion CFC inspector.
In the context of most MVC frameworks, index.cfm?event=handler.action uses the underlying framework to call a function named action within a CFC named handler. Without a framework, you have to do that manually. So if you have a CFC named controller.cfc and want to send your form data to a function named myFunction, you need to say action="controller.cfc?method=myFunction.
But that's not right either. When you submit a form, the browser expects to load the URI that's found in the action attribute. But your CFC function doesn't respond with HTML, it responds with something else. Maybe a query object, maybe JSON. This is why you would use jQuery.Ajax() to send the form data (including the data attribute values) to the CFC's function, which should return data in JSON. Once you get a response, you can continue processing on the same page or redirect to another page.
However, since you're using Framework One, I would look into the documentation on using renderData() within one of your handler functions.