Sending POST data to a page with a GET parameter with Nodejs - forms

I'm trying to send POST data to a test.php file, which handles POST data only if it was provided a specific GET data. Unfortunately I have no clue how to do that; and have been searching for about an hour.
Any help would be appreciated, as i'm currently playing around a lot with this amazing stuff.
Thanks in advance;
Some clarification:
Say you have a index.php looking like this:
<?php
if (isset($_GET['p']))
echo count($_POST) . ' -- ' . count($_GET);
else echo 'fuuu';
?>
<form action="?p" method="POST">
<input type="submit" name="lolw" value="Go" />
</form>
If you submit that form, PHP's $_GET and $_POST superglobals will both contain 1 element.
Now, lets try to run that form through nodeJS.
Here is my test case (which is merely some cutpasting from the doku):
var http = require('http');
var options = {
hostname: 'localhost',
port: 80,
path: '/test.php?lolw=1&p',
method: 'POST'
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
}).on('error', function (e) {
console.log('error in chunk');
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.toString());
});
// write data to request body
req.write('data\n');
req.end();
CLI output gives for the body:
0 -- 2 and then follows the form.
My point is: is it possible to send some parameters through GET and some others through POST, and specifying which needs to be sent through GET and which through POST ?

To make an HTTP request in node.js, you'll need to use http.request. You can set the method to "POST" and still have get parameters in your URL. You'll need to set the Content-Length header to the length of your data and the Content-Type header to application/x-www-form-urlencoded for a "standard" POST request.
Your question is pretty vague. If you're having problems with something in particular, just show your code and ask the more precise question.

Related

Delphi: REST Request with BASIC authentication

I'm using TRESTClient/THTTPBasicAuthenticator/TRESTRequest/TRESTResponse to get data from a server.
With response Ok (200), instead of receiving JSON data, I get as content this:
<script type="text/javascript">
<!-- function redirectToIndex()
{
var adresse = window.location.pathname.split('/');
var httpURL = window.location.hostname + "/" + "app"; // redirect to root
var httpsURL = "https://" + httpURL;
window.location = httpsURL;
}
redirectToIndex(); //-->
This is when TRESTRequest.Accept is empty. If I change for TRESTRequest.Accept:= 'application/json', I get an error
406 - Not Acceptable
Could you tell me what's wrong with my request?
Thank you Peter.
I managed to clarify with the API support the BASIC Authentication using the correct login/password . The documentation was inaccurate.
Access is now working as expected.

my website posts forms on http but not on https

hello I'm in the process of converting my HTTP website to https but after getting https to work no post request from forms work
I have looked around a lot but nothing really describes what I have going on here, I doubt it nginx because when I start burp suite and make the website server HTTP it sends a post request like usual, but when I run it on https the post request isn't even sent doesn't show anything on the burp suite logs
<form action="" method="post" autocomplete="off">
<p><input type="text" name=username id="username">:username
<p><input type="password" name=password id="password">:password
<p><input type="checkbox" name = "rmbm" id="rmbm">
<label for = "rmbm">remember me</label>
<p><input type=submit value=Login>
forgot password?
</form>
this is my form but I don't even see a post request
I should see a post request but I don't on burp sute
update:
hello, I've just had an epiphany. could it be the service worker and yes I was right after unregistering the service worker it worked perfectly so the problem is the service worker.
knowing this I will post the code
my service worker:
console.log('Hello from sw.js');
'use strict';
var cacheVersion = 1;
var currentCache = {
offline: 'offline-cache' + cacheVersion
};
this.addEventListener('install', event => {
event.waitUntil(
caches.open(currentCache.offline).then(function(cache) {
return cache.addAll([
'/static/html/offline.html',
'/sw.js'
]);
})
);
});
this.addEventListener('fetch', event => {
console.log("fetching");
if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
event.respondWith(
fetch(event.request.url).catch(error => {
// Return the offline page
return caches.match('/static/html/offline.html');
})
);
}
else{
event.respondWith(caches.match(event.request)
.then(function (response) {
return response || fetch(event.request);
})
);
}
});
now looking at my code it just dosnt handle post request
so i will try to fix this on my own

Sending images with AngularJS and NodeJS

Hi I am making a service to send images with users' information. For example, name, phone number, and their images to upload.
I am planning to use ng-file-upload, one of AngularJS custom dependency. And then, I am going to use Nodemailer to send all the information and images to somewhere else.
But my question is can I send other text data along with ng-file-upload? And second is can I send images with other text data through nodemailer?
Although OP has found a solution in the end, since I had the same problem I figured I'd post the whole code here for others who might struggle with that.
So here is how I combined ng-file-upload and nodemailer to upload and send attachments by e-mail using Gmail:
HTML form:
<form name="postForm" ng-submit="postArt()">
...
<input type="file" ngf-select ng-model="picFile" name="file" ngf-max-size="20MB">
...
</form>
Controller:
app.controller('ArtCtrl', ['$scope', 'Upload', function ($scope, Upload) {
$scope.postArt = function() {
var file = $scope.picFile;
console.log(file);
file.upload = Upload.upload({
url: '/api/newart/',
data: {
username: $scope.username,
email: $scope.email,
comment: $scope.comment,
file: file
}
});
}
}]);
Server:
var nodemailer = require('nodemailer');
var multipartyMiddleware = require('connect-multiparty')();
// multiparty is required to be able to access req.body.files !
app.mailTransporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: ...
pass: ...
},
tls: { rejectUnauthorized: false } // needed or Gmail might block your mails
});
app.post('/api/newart', multipartyMiddleware,function(req,res){
console.log(req.files);
mailOptions = {
from: req.body.email,
to: ...,
subject: ...
text: ...,
attachments: [{
filename: req.files.file.name,
path: req.files.file.path // 'path' will stream from the corresponding path
}]
};
app.mailTransporter.sendMail(mailOptions, function(err) {
if (err) {
console.log(err);
res.status(500).end();
}
console.log('Mail sent successfully');
res.status(200).end()
});
});
The nodemailer examples helped me figure this out!
This works for any file type. The key aspect that some people might miss out is that you need multiparty to access the uploaded file (in req.body.files). Then the most convenient way to attach it is using the path key in the attachment object.
Definitely you can send images as attachment using nodemailer.
Try this for sending image as an attachment :
var mailOptions = {
...
html: 'Embedded image: <img src="cid:unique#kreata.ee"/>',
attachments: [{
filename: 'image.png',
path: '/path/to/file',
cid: 'unique#kreata.ee' //same cid value as in the html img src
}]
}
For more reference on sending image as attachment go through nodemailer's "using Embedded documentation".
For the first part of the question:
Yes! you can send other text data along with image using ng-file-upload. It depends how you want to do it and what you want to achieve.
For example, see the code below:
HTML Template
<form name="form">
<input type="text" ng-model="name" ng-required="true">
<input type="text" ng-model="phoneNo" ng-required="true">
<div class="button" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'" ngf-accept="'image/*'" ngf-max-size="20MB" ngf-min-height="100" ngf-resize="{width: 100, height: 100}">Select</div>
<button type="submit" ng-click="submit()">submit</button>
</form>
Controller
$scope.submit = function() {
if ($scope.form.file.$valid && $scope.file) {
$scope.upload($scope.file);
}
};
// upload on file select or drop
$scope.upload = function (file) {
Upload.upload({
url: 'upload/url',
data: {file: file, 'name': $scope.name, 'phoneNo' : $scope.phoneNo}
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
});
};
Read ng-file-upload documentation completely to see understand all the things you can do along with file upload. It has many examples to make you understand everything.
I hope it helps, and answer your question.

Twitter Typeahead.js with Yahoo Finance in AJAX

I am trying to couple the new version of Typeahead.js and using it with JSON that needs to be pulled from AJAX and not from a JSON file like they have in their examples. I just can't get it to work, I don't want to cache the JSON result or anything, I want to pull it live from Yahoo.
My HTML input is <input type="text" id="symbol" name="symbol" autofocus autocomplete="off" placeholder="Symbol" onkeyup="onSymbolChange(this.value)" />
My AJAX/PHP file has this to retrieve data (this part work, I tested it with Firebug)
header('Content-type:text/html; charset=UTF-8;');
$action = (isset($_GET['action'])) ? $_GET['action'] : null;
$symbol = (isset($_GET['symbol'])) ? $_GET['symbol'] : null;
switch($action) {
case 'autocjson':
getYahooSymbolAutoComplete($symbol);
break;
}
function getYahooSymbolAutoCompleteJson($symbolChar) {
$data = #file_get_contents("http://d.yimg.com/aq/autoc?callback=YAHOO.util.ScriptNodeDataSource.callbacks&query=$symbolChar");
// parse yahoo data into a list of symbols
$result = [];
$json = json_decode(substr($data, strlen('YAHOO.util.ScriptNodeDataSource.callbacks('), -1));
foreach ($json->ResultSet->Result as $stock) {
$result[] = '('.$stock->symbol.') '.$stock->name;
}
echo json_encode(['symbols' => $result]);
}
The JS file (this is where I'm struggling)
function onSymbolChange(symbolChar) {
$.ajax({
url: 'yahoo_autocomplete_ajax.php',
type: 'GET',
dataType: 'json',
data: {
action: 'autocjson',
symbol: symbolChar
},
success: function(response) {
$('#symbol').typeahead({
name: 'symbol',
remote: response.symbols
});
}
});
}
I don't think that I'm suppose to attach a typeahead inside an AJAX success response, but I don't see much examples with AJAX (except for a previous version of typeahead)... I see the JSON response with Firebug after typing a character but the input doesn't react so good. Any guidance would really be appreciated, I'm working on a proof of concept at this point... It's also worth to know that I'm using AJAX because I am in HTTPS and using a direct http to Yahoo API is giving all kind of problems with Chrome and new Firefox for insecure page.
UPDATE
To make it to work, thanks to Hieu Nguyen, I had to modify the AJAX JSON response from this echo json_encode(['symbols' => $result]); to instead this echo json_encode($result); and modify the JS file to use the code as suggested here:
$('#symbol').typeahead({
name: 'symbol',
remote: 'yahoo_autocomplete_ajax.php?action=autocjson&symbol=%QUERY'
});
I have to do it in reverse, i.e: hook the ajax call inside typeahead remote handler. You can try:
$('#symbol').typeahead({
name: 'symbol',
remote: '/yahoo_autocomplete_ajax.php?action=autocjson&symbol=%QUERY'
});
You don't have to create onSymbolChange() function since typeahead will take care of that already.
You can also filter and debug the response from backend by using:
$('#symbol').typeahead({
name: 'symbol',
remote: {
url: '/yahoo_autocomplete_ajax.php?action=autocjson&symbol=%QUERY',
filter: function(resp) {
var dataset = [];
console.log(resp); // debug the response here
// do some filtering if needed with the response
return dataset;
}
}
});
Hope it helps!

JSON object parsing error using jQuery Form Plugin

Environment: JQuery Form Plugin, jQuery 1.7.1, Zend Framework 1.11.11.
Cannot figure out why jQuery won't parse my json object if I specify an url other than a php file.
The form is as follows:
<form id="imageform" enctype="multipart/form-data">
Upload your image <input type="file" name="photoimg" id="photoimg" />
<input type="submit" id ="button" value="Send" />
</form>
The javascript triggering the ajax request is:
<script type="text/javascript" >
$(document).ready(function() {
var options = {
type: "POST",
url: "<?php $this->baseURL();?>/contact/upload",
dataType: 'json',
success: function(result) {
console.log(result);
},
error: function(ob,errStr) {
console.log(ob);
alert('There was an error processing your request. Please try again. '+errStr);
}
};
$("#imageform").ajaxForm(options);
});
</script>
The code in my zend controller is:
class ContactController extends BaseController {
public function init() {
/* Initialize action controller here */
}
public function indexAction() {
}
public function uploadAction() {
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$image = $_FILES['photoimg']['tmp_name'];
$im = new imagick($image);
$im->pingImage($image);
$im->readImage($image);
$im->thumbnailImage(75, null);
$im->writeImage('userImages/test/test_thumb.jpg');
$im->destroy();
echo json_encode(array("status" => "success", "message" => "posted successfully"));
}
else
echo json_encode(array("status" => "fail", "message" => "not posted successfully"));
}
}
When I create an upload.php file with the above code, and modify the url from the ajax request to
url: "upload.php",
i don't run into that parsing error, and the json object is properly returned. Any help to figure out what I'm doing wrong would be greatly appreciated! Thanks.
You need either to disable layouts, or using an action helper such as ContextSwitch or AjaxContext (even better).
First option:
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout->disableLayout();
And for the second option, using AjaxContext, you should add in your _init() method:
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('upload', 'json')
->initContext();
This will disable automatically disable layouts and send a json header response.
So, instead of your two json_encode lines, you should write:
$this->status = "success";
$this->message = "posted successfully";
and
$this->status = "fail";
$this->message = "not posted successfully";
In order to set what to send back to the client, you simply have to assign whatever content you want into view variables, and these variables will be automatically convert to json (through Zend_Json).
Also, in order to tell your controller which action should be triggered, you need to add /format/json at the end of your URL in your jQuery script as follow:
url: "<?php $this->baseURL();?>/contact/upload/format/json",
More information about AjaxContext in the manual.
Is the Content-type header being properly set as "application/json" when returning your JSON?