I am playing with dart http server and I'm not sure how to read the actual content sent in the http request: "{'text':'some text data.'}"
import 'dart:io';
void main() {
HttpServer.bind('127.0.0.1', 3000).then((server){
server.listen((HttpRequest request) {
print("request made");
request.response.write('''
<html>
<head>
</head>
<body>
<pre>
HELLO:
request info:
method: ${request.method}
uri: ${request.uri}
content length: ${request.contentLength}
content : //HOW DO I GET THIS?
</pre>
<script>
var req = new XMLHttpRequest();
req.open("POST","/a_demonstration");
req.send("{'text':'some text data.'}");
</script>
</body>
</html>
''');
request.response.close();
});
});
}
You can use :
import 'dart:convert' show utf8;
Future<String> content = utf8.decodeStream(request);
Alexandre Ardhuin gave the short and correct answer, for anyone wanting to see full code:
import 'dart:io';
import 'dart:convert' show UTF8;
void main() {
HttpServer.bind('127.0.0.1', 3000).then((server){
server.listen((HttpRequest request) {
print("request made");
if(request.contentLength == -1){
_sendResponse(request, '');
}else{
UTF8.decodeStream(request).then((data)=>_sendResponse(request,data));
}
});
});
}
_sendResponse(HttpRequest request, String requestData){
request.response.write('''
<html>
<head>
</head>
<body>
<pre>
HELLO:
request info:
method: ${request.method}
uri: ${request.uri}
content length: ${request.contentLength}
content: ${requestData}
</pre>
<script>
var req = new XMLHttpRequest();
req.open("POST","/a_demonstration");
req.send("{'text':'some text data.'}");
</script>
</body>
</html>
''');
request.response.close();
}
Related
I am trying to build a React Native app using expo and firebase authentication. The email/password authentication is working fine but the phone number authentication is failing because of the applicationVerifier.
I have tried to use 'react-native-firebase' but that is also not working and giving error.
[Error: RecaptchaVerifier is only supported in a browser HTTP/HTTPS environment with DOM support.]
Thanks.
You need to make .html file and put this code..
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<title>Entering captcha</title>
</head>
<body>
<p style="text-align: center; font-size: 1.2em;">Please, enter captcha for continue<p/>
<button id="continue-btn" style="display:none">Continue to app</button>
<script src="https://www.gstatic.com/firebasejs/5.10.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.10.1/firebase-auth.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyCy6HyqIV5Q_A5lllIxZgePSmKq-Q8eqiw",
authDomain: "onsignledemo.firebaseapp.com",
databaseURL: "https://onsignledemo.firebaseio.com",
projectId: "onsignledemo",
storageBucket: "onsignledemo.appspot.com",
messagingSenderId: "223114260821"
};
firebase.initializeApp(config);
</script> <script>
function getToken(callback) {
var container = document.createElement('div');
container.id = 'captcha';
document.body.appendChild(container);
var captcha = new firebase.auth.RecaptchaVerifier('captcha', {
'size': 'normal',
'callback': function(token) {
callback(token);
},
'expired-callback': function() {
callback('');
}
});
captcha.render().then(function() {
captcha.verify();
});
}
function sendTokenToApp(token) {
var baseUri = decodeURIComponent(location.search.replace(/^\?appurl\=/, ''));
const finalUrl = location.href = baseUri + '/?token=' + encodeURIComponent(token);
const continueBtn = document.querySelector('#continue-btn');
console.log(finalUrl);
// continueBtn.onclick = (event)=>{
// window.open(finalUrl,'_blank')
// }
continueBtn.style.display = "block";
}
document.addEventListener('DOMContentLoaded', function() {
getToken(sendTokenToApp);
});
</script>
</body>
</html>
and put this file in to your running server and load your URL in to react- native Webview before sending confirmation code and after verify this CAPTCHA send confirmation code...
I trying to create a test against a simple service, but I am getting an error that says "TypeError: Object doesn't support property or method 'map'" When I run this service for real (not as a test) it works fine and I don't have any issues. This is the first time I'm trying to get a test setup for Angular2, so I could be missing something. Here are my components.
recentActivity.service.ts
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import * as toPromise from 'rxjs/add/operator/toPromise';
import * as map from 'rxjs/add/operator/map';
import { RecentActivity } from './recentActivity.model';
#Injectable()
export class RecentActivityService {
private baseUrl = '/RecentActivity/';
constructor(private http: Http) {
}
get(): Observable<any> {
//return undefined;
return this.http
.get(this.baseUrl + 'Get')
.map((response: Response) => response.json())
//.toPromise()
;
}
}
recentActivity.spec.ts
import { async, describe, it, expect, inject, beforeEach, beforeEachProviders } from '#angular/core/testing';
import { Http, BaseRequestOptions, Response, ResponseOptions } from '#angular/http';
import { MockBackend, MockConnection } from '#angular/http/testing';
import { RecentActivity } from './recentActivity.model';
import { RecentActivityService } from './recentActivity.service';
describe('Recent Activity Service', () => {
let service: RecentActivityService;
let mockBackend: MockBackend;
const mockResponseData: RecentActivity[] = [
{ Name: 'Test Result 1', Url: '#/TestResult1' },
{ Name: 'Test Result 2', Url: '#/TestResult2' },
{ Name: 'Test Result 3', Url: '#/TestResult3' }
];
beforeEachProviders(() => [
RecentActivityService,
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory: (backend, options) => new Http(backend, options),
deps: [MockBackend, BaseRequestOptions]
}
]);
beforeEach(inject([RecentActivityService, MockBackend], (ras, mb) => {
service = ras;
mockBackend = mb;
}));
it('Can load list of recent activities', (done) => {
mockBackend.connections.subscribe((connection: MockConnection) => {
const responseOpts = new ResponseOptions({ body: JSON.stringify(mockResponseData) });
connection.mockRespond(new Response(responseOpts));
});
service.get()
.subscribe((results: RecentActivity[]) => {
expect(results.length).toEqual(3);
expect(results[0].Name).toEqual('Test Result 1');
expect(results[1].Name).toEqual('Test Result 2');
expect(results[2].Name).toEqual('Test Result 3');
done();
});
});
});
unit-tests.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Unit Tests</title>
<link rel="stylesheet" href="./libs/jasmine-core/lib/jasmine-core/jasmine.css">
<script src="./libs/jasmine-core/lib/jasmine-core/jasmine.js"></script>
<script src="./libs/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
<script src="./libs/jasmine-core/lib/jasmine-core/boot.js"></script>
<script src="./libs/core-js/client/shim.min.js"></script>
<script src="./libs/zone.js/dist/zone.js"></script>
<script src="./libs/reflect-metadata/Reflect.js"></script>
<script src="./libs/systemjs/dist/system.src.js"></script>
<script src="./libs/rxjs/bundles/Rx.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/underscore/underscore.js"></script>
<script src="~/lib/moment/moment.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="./systemjs.config.js"></script>
<script>
// #2. Configure systemjs to use the .js extension
// for imports from the app folder
System.config({
packages: {
'app': { defaultExtension: 'js' }
}
});
// #3. Import the spec file explicitly
Promise.all([
System.import('app/recentActivity/recentActivity.spec'),
System.import('app/pipes/styleVisibility.spec')
])
// #4. wait for all imports to load ...
// then re-execute `window.onload` which
// triggers the Jasmine test-runner start
// or explain what went wrong.
.then(window.onload)
.catch(console.error.bind(console));
</script>
</head>
<body>
</body>
</html>
I've tried to piece together the pieces to get this to work, but I can't figure out what I'm missing. Also as a side note I'm using Visual Studio 2015 and that is also giving a warning saying "Property map does not exist on type 'Observable'".
Like I mentioned everything works when I run this service for real and it returns my information from my backend no problem.
All I had to do was change the imports in the recentActivity.service.ts file to be
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
I still get an error (red squiggly) In Visual Studio, so if somebody could tell me how to get rid of that I would appreciate it.
The above solution works for me too. But since I was also using .do and .catch, I had to import those as well:
import 'rxjs/add/operator.do;
import 'rxjs/add/operator.catch;
Hope this helps others also.
So I'm working on a site where the user logs into my Soundcloud app and automatically follows me. I am able to login but it doesn't follow. I can't seem to figure this out.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://connect.soundcloud.com/sdk/sdk-3.0.0.js"></script>
<script>
SC.initialize({
client_id: '551f515f1sa1f51sa51f65sa165',
redirect_uri: 'http://mydomain/callback.html'
});
SC.connect().then(function() {
// Follow user with ID 3207
SC.put('/me/followings/3207');
});
</script>
</head>
<body>
<img onclick="SC.connect()" src="http://connect.soundcloud.com/2/btn-connect-sc-l.png">
</body>
</html>
Any help would be appreciated!
Try doing this:
<script type="text/javascript">
SC.initialize({
client_id: "551f515f1sa1f51sa51f65sa165",
redirect_uri: "http://mydomain/callback.html",
scope: "non-expiring"
});
function SC_login()
{ SC.connect(function() {
SC.get("/me", function(me) {
/* Follow */
SC.put('/me/followings/215527712');
});
});
}
</script>
and on your image
<img onclick="SC_login()" src="http://connect.soundcloud.com/2/btn-connect-sc-l.png">
Also, could you post your callback.html so I could take a look at it?
I have a node.js-app running on the same machine on port 8080 with different channels. The communication between my jQuery-site and my .NET endpoint works perfectly.
My Site:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WebSocket-Test</title>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
$(function() {
$('button').click(function() {
var socket = io.connect('http://localhost:4000');
socket.on($('#username').val(), function (data) {
console.log(data);
socket.emit('my other event', { my: data });
});
});
});
</script>
<input type="text" id="username" />
<button>connect</button>
</body>
</html>
My node.js-server:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(4000);
var count = 0;
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
setInterval(function () {
socket.emit('daniel', { hello: 'Waited two seconds!'});
}, 2000);
socket.emit('daniel', { hello: 'world' });
socket.emit('stefan', { hello: 'world2' });
socket.on('my other event', function (data) {
console.log(data);
});
});
My question is, how can I emmit a message from my .NET backend via node.js?
After my page is loaded I do have a window.io-object. What is the best approach? Just do an eval on the io-object with emmit and the channel or can I pass an object or json-thing to my node.js-server?
My target is, to send an event-driven message. When a new row is inserted into my MSQL-DB a message should be send to the channels.
One thing that you can do, is simply ping the Node.js server when there's an update with the details. You can do this over straight http/https.
Basically, when .NET updates the db, it can fire off a quick POST to a node.js endpoint with the data package that you want to roll out to users.
I would like to use html2canvas but it is not clear enough how to use it in the documentation. What libraries I should include ? and then is this peace of code just what I need ? What about the proxy ? and How I could save the screen shot after it's taken ?
$('body').html2canvas();
var queue = html2canvas.Parse();
var canvas = html2canvas.Renderer(queue,{elements:{length:1}});
var img = canvas.toDataURL()
window.open(img);
For me, it was working this way:
$('#map').html2canvas({
onrendered: function( canvas ) {
var img = canvas.toDataURL()
window.open(img);
}
The current latest version works this way:
html2canvas($('#map'),
{
onrendered: function(canvas) {
cvs = canvas.toDataURL('image/png');
window.open(cvs)
}
});
Here's a minimal, complete example that shows how to convert the DOM to canvas with html2canvas, convert the canvas to base64, and finally trigger a download.
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
</head>
<body>
<h1>Hello World</h1>
<script>
(async () => {
const canvas = await html2canvas(document.body);
const base64 = canvas.toDataURL();
const a = document.createElement("a");
a.href = base64;
a.download = "html2canvas-test.png";
a.click();
})();
</script>
</body>
</html>
I'm not sure what you mean about a proxy.