Flutter: how to create post request with form data same js code - flutter

I want to upload an image to the server with flutter, in js t use form data with input file but with flutter I don't know what to do.
in js:
formData.append("file", e.clipboardData.files[0]);
formData.append("session", sessionid);
formData.append("fileindex", fileListIndex);
var hostname = window.location.hostname;
var protocol = window.location.protocol;
if (hostname === "localhost") {
xhr.open("POST", "http://localhost:9999/" + uploadpoint, true);
} else if (hostname === "www.aladin.finance") {
xhr.open("POST", protocol + "//uploadfile.aladin.finance" + "/"
+ uploadpoint, true);
} else {
xhr.open("POST", protocol + "//uploadfile." + hostname + "/"
+ uploadpoint, true);
}
xhr.withCredentials = true;
xhr.send(formData);

Flutter has this great package called Dio to handle all sort of http requests. It's very easy to do what you want with it. Check this: https://pub.dev/packages/dio#sending-formdata

Related

ionic 3 header not sending Authorizaqtion 'bearer "token"' to server

Im doing a login screen that takes a username and password.
if the login was successful the server will return a token.
then im trying to call another function to get user info but the authorization header is not being passed.
im trying my server method on postman and its working fine so i believe the problem is in the headers. May someone please advise me on what should be done?
let url = urlConst.Login;
let params1 = new HttpParams();
let loader = this.loadingcontroller.create({
content: stringEngConst.signinngin
});
let attributes = {
username: this.uname.value.toLowerCase(),
password: this.password.value,
grant_type: "password"
};
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let body = 'username=' + this.uname.value.toLowerCase() + '&password=' + this.password.value + '&grant_type=password';
let data: Observable < any > = this.http.post(url, body, {
headers: headers
});
loader.present().then(() => {
data.subscribe(result => {
if (result.access_token != null) {
this.signintoken = result.access_token;
this.storage.set(storageConst.SIGN_IN_TOKEN, result.token_type + " " + result.access_token);
headers.append('Authorization', 'Bearer ' + this.signintoken);
let url1 = 'http://localhost:57940/API/Account/GetUserInfo/';
let info: Observable < any > = this.http.get(url1, {
headers: headers
});
info.subscribe(result => {
/*Do Something*/
});
}
Please Note that result.access_token != null is true. and i am successfully getting the token back. But it is not being passed again to the second url (info)
Looks like this SO post may solve things for you: https://stackoverflow.com/a/47805759/6599076
You may want to use:
headers = headers.append('Authorization', 'Bearer ' + this.signintoken);
You are using the same headers as for the first http request:
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
Depending on your end point for the subsequent call it might be that you need to set headers differently:
Try creating new headers with
var headers2 = new HttpHeaders();
headers.append('Content-Type', 'application/json');
Or get rid of Content-Type completely depending on what your end point expects.
Also if you are using Ionic 3 its worth to check which Http module you are using (HttpClient or the older one) as there are some differences in how these tend to handle request options.

Facebook Messenger API "request body undefined"

After following all the steps as per the standard documentation, I am getting req.body undefined in my webhook:
app.post('/webhook/', function(req, res) {
console.log("message received " + req.body);
if(!req.body){
console.log("no request body found");
res.sendStatus(200);
return;
}
messaging_events = req.body.entry[0].messaging;
for (i = 0; i < messaging_events.length; i++) {
event = req.body.entry[0].messaging[i];
sender = event.sender.id;
console.log("sender " + event.sender + ", message " + event.message.text);
if (event.message && event.message.text) {
text = event.message.text;
// Handle a text message from this sender
sendTextMessage(sender, "Text received, echo: "+ text.substring(0, 200));
}
}
res.sendStatus(200);
});
Edit
Do I need to Approve the Bot before I can test? also my Facebook Page is Live
Latest versions of Express (4.x) has unbundled the middleware from the core framework. If you need body parser, you need to install it separately
npm install body-parser --save
and then do this in your code
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

Nodejs - websocket-node module: How to make multi-client socket-server works?

I created a socket server using websocket module with this configuration taken from this example (with some changes):
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(5050, function() {
console.log((new Date()) + ' Server is listening on port 5050');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
I create my own client in html :
<html>
<head>
<script src='./js/jquery1-11-3-min.js'></script>
<script>
$(document).ready(function (){
buildwebsocket();
});
var ws;
function buildwebsocket(){
ws = new WebSocket("ws://192.168.0.96:5050",'echo-protocol');
ws.onopen = function(evt) { onOpen(evt) };
ws.onclose = function(evt) { onClose(evt) };
ws.onmessage = function(evt) { onMessage(evt) };
ws.onerror = function(evt) { onError(evt) };
}
function onOpen(ev){
//alert("konek men! mantap! :D");
$("#recmsg").append("connected!<br>");
}
function onClose(ev){
$("#recmsg").append("connection closed!<br>");
}
function onMessage(ev){
//alert("ada pesan datang!");
$("#recmsg").append(ev.data+"<br>");
}
function onError(ev){
$("#recmsg").append("connecting error!<br>");
}
function doSend(){
//writeToScreen("SENT: " + message);
var message = $("#pesan").val();
ws.send(message);
} function doClose(){
ws.close();
}
//function writeToScreen(message){
//var pre = document.createElement("p");
//pre.style.wordWrap = "break-word";
//pre.innerHTML = message;
//output.appendChild(pre);
//}
//window.addEventListener("load", init, false);
</script>
</head>
<body>
<button onclick='doClose()'>Close</button>
<textarea id='pesan'></textarea><br>
<button onclick='doSend()'>Kirim!</button>
<br>
received message
<div id='recmsg'>
</div>
</body>
</html>
The connection between client (first client) and the server was successfully established. I try to send messages from first client, then the server receives the message without any promblem, and then the message sent back to the first client, and the first client receives it. I can say the connection and the socket works well.
I try to establish another connection (second client), so I open the second client in another device. The connection is good. But, when I send messages from the first or the second client, the first client doesn't get the response but the second client gets it.
And if open the third client and then send a message, the first and the second client don't get the response. Only the last connected client receives the response from server, and there's no client receives any error messages.
Is it the cons of the module? or the server configuration must be changed/added?
Can I establish multi-client-supported-socket-server using this module?
You're not storing the connections on the server side. You're just setting them up on the server to communicate directly back and forth to the server. If you want messages going to the server to be sent back out to everyone, you need to set up the .on('message', ...) function for each connection on the server to have that behavior. To do this, you'll need to store the connections as they are created. Try this:
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(5050, function() {
console.log((new Date()) + ' Server is listening on port 5050');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
//create an array to hold your connections
var connections = [];
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
//store the new connection in your array of connections
connections.push(connection);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
//send the received message to all of the
//connections in the connection array
for(var i = 0; i < connections.length; i++) {
connections[i].sendUTF(message.utf8Data);
}
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});

Problems uploading jpg with OneDrive Rest Api

For this HTML5 phone App I have to use the OneDrive REST API.
I managed to upload the file, but the file up on the server is not in .jpg format and won't display in a jpg viewer. After logging in through the REST API and getting a token back, I used XMLHttpRequest to PUT the file. I've tried passing it up as an ArrayBuffer and as a base64 encoded string. In each case the file makes it there, but is not decoded properly. I figured I needed to tell the webserver how to decode the file with "request.setRequestHeader('Content-Type', 'image/jpg')" ,but I get back the following error message from the OneDrive server:
"error": {
"code": "request_body_invalid_media_type",
"message": "The Content-Type header 'text/plain' isn't supported."
}
this.uploadFile = function (token, fileUri,fileName, fileTools, success, fail) {
var me = app.log('||Microsoft.uploadFile||');
fileTools.readFileContent(fileUri, 'dataUrl', gotData, fileError);
function fileError(err) {
app.logError(me + '::fileError:::' + err);
}
function gotData(base64String) {
var request = new XMLHttpRequest;
app.log(me + '::token::' + token);
request.open("PUT", "https://apis.live.net/v5.0/me/skydrive/files/" + fileName + "?access_token=" + token, true);
request.setRequestHeader('Content-Type', 'text/plain');
//request.setRequestHeader('Content-Type', 'image/jpg');
//request.setRequestHeader('Content-Transfer-Encoding', 'base64;charset=utf-8');
request.onload = function (e) {
app.log(request.responseText);
success(e);
};
request.onerror = function (e) {
app.log(me + '::7::');
fail(e.error.message);
};
app.log(me + '::8::' + base64String.substr(0,100));
var b = new Base64Stuff();
var aBuffer = b.base64ToBuffer(b.removeBase64jpgHeader(base64String));
request.send(aBuffer);
//request.send(base64String);
}
}
try
request.setRequestHeader('Content-Type', '');

phonegap - using external site as app - facebook login

I'm building a app site running through phone gap. Phone gap simply checks the user has internet connection and loads an external web app into the frame. I can navigat through the site fine with no blibs but as soon as I try the login to Facebook (either PHP redirect or javascript SDK) the app suddenly gets its navbar back or opens a new window (javascript SDK).
Is there anyway I can prevent this?
regards
It took some doing but using the ChildBrowser plugin, I've managed to login! (this is for android) I've used some code from a facebook connect plugin which didnt work for me, re wrote some stuffs so I could understand it and now works. Chears Juicy Scripter!
var fb_success = 'https://www.facebook.com/connect/login_success.html';
var fb_logout = 'https://www.facebook.com/connect/login_failed.html';
var fb_logout_ = 'http://m.facebook.com/logout.php?confirm=1&next=' + fb_logout;
var authorize_url = '';
var my_client_id = '##################';
var my_secret = '######################';
var my_type = 'user_agent';
var my_display = 'touch';
var token = false;
var fb_code = false;
var device_ready = false;
var ajax_url = '';
function logged_in(){
// alert('do what you need to do!');
}
function fb_force_logout(){
}
function fb_auth_check(){
console.log('fb_auth_check()');
if( fb_code !== false ) {
console.log('ajax test instigated...');
ajax_url = 'https://graph.facebook.com/oauth/access_token?client_id=' + encodeURIComponent(my_client_id) + '&client_secret=' + encodeURIComponent(my_secret) + '&code=' + encodeURIComponent(fb_code) + '&redirect_uri=' + fb_success;
$.ajax({
url: ajax_url,
type: 'POST',
success: function(html){
token = html.split("=")[1];
console.log('success! token = ' + token);
window.plugins.childBrowser.close();
fb_init();
},
error: function(error) {
console.log('there was an error...' + ajax_url);
window.plugins.childBrowser.close();
}
});
}
}
function fb_track_redirects(loc){
console.log('redirect tracked... ' + loc);
if ( loc.indexOf(fb_success) >= 0 || loc.indexOf(fb_success) > -1 ) {
fb_code = loc.match(/code=(.*)$/)[1]
console.log('success redirect... fb_code=' + fb_code);
fb_auth_check();
window.plugins.childBrowser.close();
} else if ( loc.indexOf(fb_logout) >= 0 || loc.indexOf(fb_logout) > -1 ) {
window.plugins.childBrowser.close();
}
}
function inner_init(){
console.log('inner_init()');
if( token === false ) {
console.log('token was false...');
authorize_url += "https://graph.facebook.com/oauth/authorize?";
authorize_url += "client_id=" + encodeURIComponent(my_client_id);
authorize_url += "&redirect_uri=" + encodeURIComponent(fb_success);
authorize_url += "&display=" + encodeURIComponent(my_display);
authorize_url += "&scope=publish_stream,offline_access";
console.log('instigated location change...');
window.plugins.childBrowser.onLocationChange = function(loc){
fb_track_redirects(loc);
}
console.log('open Facebbok login window');
window.plugins.childBrowser.showWebPage(authorize_url);
}else{
logged_in();
}
}
function fb_init(){
console.log('fb_init()');
if( device_ready === false ) {
console.log('first device run...');
document.addEventListener("deviceready", function(){
device_ready = true;
console.log('device ready...');
inner_init();
}, false);
}else{
inner_init();
}
}
$(document).ready(function(){
$('#login').bind('click', function(){
fb_init();
return false;
})
});
</script>
This is how it works for all apps native or web without patching the SDK code.
This is probably can be done, but will require digging into code. The question is do you really need it? This is a desired behavior.
You can try to use PhoneGap Facebook plugin and enable Single Sign On so native Facebook App if exists will be opened instead of browser to authenticate the user.
BTW,
Apps that are just external sites wrapped mostly rejected in app store.
Update:
Where is some points that may be also helpful in answer (by Facebook employee) to similar question How can I use an access token to circumvent FB.login().
Also have a look on ChildBrowser PhoneGap plugin (and Example).