react-router - server side rendering match - match

I have this on my server
app.get('*', function(req, res) {
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
const body = renderToString(<RouterContext {...renderProps} />)
res.send(`
<!DOCTYPE html>
<html>
<head>
<link href="//cdn.muicss.com/mui-0.6.5/css/mui.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="root">${body}</div>
<script defer src="assets/app.js"></script>
</body>
</html>
`)
})
})
And this on the client side
import { Router, hashHistory, browserHistory, match } from 'react-router'
let history = browserHistory
//client side, will become app.js
match({ routes, location, history }, (error, redirectLocation, renderProps) => {
render(<Router {...renderProps} />, document.getElementById('root'))
})
the problem
It works only when I remove the (let history = browserHistory), but it adds the /#/ hash prefix to my url(which I don't want to happen).
When I leave the let (history = browserHistory) there, it throws an error
Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
(client) < ! -- react-empty: 1 -
(server) < section data-reactro
The error message is pretty clear, however, I don't understand why it works with the hashHistory but fails with the browserHistory

version incompatibility issue
solution
{
"history": "^2.1.2",
"react-router": "~2.5.2"
}
links:
https://github.com/reactjs/react-router/issues/3003

Related

Best way to stream audio data between the browser and FastAPI

I have some basic Server and Client Side code with FastAPI, but I am trying to find the best way to read in that data for a live application that does some audio processing. I am not sure how to approach this, as FastAPI can only read the data from the client as bytes. Should I even bother converting it to a Blob after recording? Maybe use HTTP for simplicity (just building a prototype so it does not need to be optimal)? I also read about RTSP but I can't seem to find any good resources for it, so I would appreciate some way to point me in the right direction. Thanks for any advice!
Client
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>helloworld</h1>
<script>
var ws = new WebSocket("ws://localhost:8000/ws", 'echo-protocol');
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
const mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start(5000);
mediaRecorder.addEventListener("dataavailable", event => {
console.log("sending audio");
const audioBlob = new Blob([event.data], {type: 'audio/mp3'});
ws.send(audioBlob);
console.log("sent audio");
});
});
</script>
</body>
</html>
Server
from fastapi import FastAPI, WebSocket, Request
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
#app.get("/")
def read_root(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
#app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_bytes()

How do i properly install flask-socketIO?

I have installed multiple times Flask-socketio on my mac, closely reading the instructions and installing the requirements (eventlet/gevent). Athough when i run my simple code to test, it either says that i have not imported the modules or show nothing until i open index.html in my browser where it then displays :
The client is using an unsupported version of the Socket.IO or Engine.IO protocols (further occurrences of this error will be logged with level INFO)
Here is my app.py code:
from flask import Flask
from flask_socketio import SocketIO, send
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hello'
socketio = SocketIO(app, cors_allowed_origins='*')
#socketio.on('message')
def handle(msg):
print("message: "+msg)
send(msg, bradcast=True)
if __name__ == '__main__':
socketio.run(app)
And here is my terminal window:
Here is my index.html code (if needed):
<html>
<head>
<title>Chat Room</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
var socket = io.connect('http://127.0.0.1:5000');
socket.on('connect', function() {
socket.send('User has connected!');
});
socket.on('message', function(msg) {
$("#messages").append('<li>'+msg+'</li>');
console.log('Received message');
});
$('#sendbutton').on('click', function() {
socket.send($('#myMessage').val());
$('#myMessage').val('');
});
});
</script>
<ul id="messages"></ul>
<input type="text" id="myMessage">
<button id="sendbutton">Send</button>
</body>
</html>
Thank you for your help
Check the Flask-SocketIO docs for information about version compatibility.
You have installed Flask-SocketIO version 5, so you need version 3 of the JavaScript client, but you have 1.4.8.
Use this CDN URL instead for version 3.0.5: https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.5/socket.io.min.js

Integration between Axios and RequireJS fail

I have a error in integration between RequireJS and Axios:
<HEAD>
<script src="3party/require.js"></script>
<SCRIPT>
//work!
requirejs(['/bower_components/jquery/dist/jquery'],()=>{
console.debug($);
})
//error
requirejs(['/bower_components/axios/dist/axios'],()=>{
axios.get('https://httpbin.org/get').then(function(response){
console.log(response.status); // ex.: 200
});
});
</SCRIPT>
</HEAD
The URL is a test service, the error below occurs.
require.js:5 Uncaught Error: Script error for "/bower_components/axios/dist/axios"
https://requirejs.org/docs/errors.html#scripterror
at makeError (require.js:5)
Any URL, or even the below line, the error occurs:
console.debug(axios);
I am using the below version:
"axios": "^0.19.2",
I've checked the AXIOS code and it does support AMD. So you need to use it as a regular AMD:
<HEAD>
<script src="3party/require.js"></script>
<SCRIPT>
requirejs(['/bower_components/jquery/dist/jquery'],()=>{
console.debug($);
})
requirejs(['/bower_components/axios/dist/axios'],(axios)=>{ // axios is given as a argument to a your callback
axios.get('https://httpbin.org/get').then(function(response){
console.log(response.status); // ex.: 200
});
});
</SCRIPT>
</HEAD>
AXIOS will not be available as global but as a local module when you require it :)

How to implement OAuth.io using Ionic Framework for LinkedIn?

I have created the LinkedIn app and retrieved the client id and client_secret.
Now inside the integrated api of OAuth.io created an api and have added the keys and permission scope.
I want to run this project using Ionic Framework. What should be done to achieve it.
P.S: I am new to Ionic Framework and OAuth.io. So please don't mind my style of asking the question.
whole index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="js/ng-cordova.min.js"></script>
<script src="js/ng-cordova-oauth.min.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-controller="MainCtrl">
<button class="button" ng-click="linkedInLogin()">Login via LinkedIn</button>
</body>
</html>
whole app.js:
angular.module('starter', ['ionic', 'ngCordova', 'ngCordovaOauth'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.controller("MainCtrl", function($scope, $cordovaOauth) {
document.addEventListener( "deviceready", onDeviceReady );
function onDeviceReady( event ) {
// on button click code
$scope.linkedInLogin = function(){
OAuth.initialize('07IxSBnzVoGGQL2MpvXjSYakagE')
OAuth.popup('linkedin').done(function(result) {
// Here you will get access token
console.log(result)
result.me().done(function(data) {
// Here you will get basic profile details of user
console.log(data);
})
});
};
}
});
Please go through the steps and below code:
1) create a project from terminal as ionic start linkedinlogin blank
2)cd linkedinlogin project
3)Add the required platform in terminal as ionic add platform ****
4)Add the ng-cordova.min.js file above the cordova.ja file in our project
5)Install ng-cordova-oauth as bower install ng-cordova-oauth -S
6)Then include ng-cordova-oauth.min.js file in index.html
7)Inject 'ngCordova' and 'ngCordovaOauth' as dependency in app.js file
8)In index.html create a button as login via linkedin
9)In app.js create a Controller with below code
10)Please update your cordova platform if the above plugin doesn't work
$cordovaOauth.linkedin(clientId, clientSecret, ['r_basicprofile', 'r_emailaddress']).then(function(success){
//Here you will get the access_token
console.log(JSON.stringify(success));
$http({method:"GET", url:"https://api.linkedin.com/v1/people/~:(email-address,first-name,last-name,picture-url)?format=json&oauth2_access_token="+success.access_token}).success(function(response){
// In response we will get firstname, lastname, emailaddress and picture url
// Note: If image is not uploaded in linkedIn account, we can't get image url
console.log(response);
}, function(error){
console.log(error);
})
}, function(error){
console.log(error);
})
I thing you read the ngCordova plugins.
Using oauth.io i have implemented login via linkedin:
Please follow the steps:
1. Create a app in oauth.io and get public key.
2. Click on the Integrated APIs menu from the left side bar.
3. Now click on ADD APIs green button on the right top corner.
4. Now Search and select LinkedIn.
5. Now add the Client id and Client Secret in keys and permission scope.
6. use below command to add plugin to project:
cordova plugin add https://github.com/oauth-io/oauth-phonegap
7. For controller code check below code.
document.addEventListener( "deviceready", onDeviceReady );
function onDeviceReady( event ) {
// on button click code
$scope.linkedInLogin = function(){
OAuth.initialize('your public key')
OAuth.popup('linkedin').done(function(result) {
// Here you will get access token
console.log(result)
result.me().done(function(data) {
// Here you will get basic profile details of user
console.log(data);
})
});
};
}
Hope it may be help you..

backbone.js - problem loading using models defined in separate file

I'm running Sinatra with Backbone.js. I'm trying to split up my models, views, etc so they aren't all lumped into a single JS file. Right now I have the following.
index.html
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<script src="scripts/underscore-min.js"></script>
<script src="scripts/jquery-1.5.min.js"></script>
<script src="scripts/backbone-min.js"></script>
<script src="scripts/models.js"></script>
...
models.js
Models = {
var Event = Backbone.Model.extend({
});
var Events = Backbone.Collection.extend({
url: '/events',
model: Event
});
};
So models.js expects that Backbone.js has been loaded, which it should have been based on index.html, however, I'm getting a JavaScript error in models.js where I reference Backbone.Model.
Any ideas on what I'm missing here?
That isn't valid javascript. Something like this is more likely to work :
Models = {}
Models.Event = Backbone.Model.extend({
});
Models.Events = Backbone.Collection.extend({
url: '/events',
model: Event
});