WebSocketException: Connection to url.. was not upgraded to websocket. It is working fine in angular but not in flutter why? - flutter

I have tried to do in 2 ways it's not working while it is working in angular
way
var channel = IOWebSocketChannel.connect(
Uri.parse('wss://......./...../mywebsockets'),
headers: {
'Connection': 'Upgrade',
'Upgrade': 'websocket'
}
);
channel.stream.listen((event) {
print(event);
});
2nd way
StompClient client = StompClient(
config: StompConfig.SockJS(
url: 'https://....../.../mywebsockets',
webSocketConnectHeaders: {
'Upgrade': 'websocket',
'Connection': 'Upgrade',
},
onConnect: (StompFrame connectFrame) {
print('connected');
},
onWebSocketError: (dynamic error) => print(error.toString()),
onStompError: (d) => print("stomp error"),
onDisconnect: (d)=> print("disconnect"),
)
);
At backend(java) we removed .withSockJs() it is not working. Removed handshake still not working.

The problem is that WebSocket source code is actually ditching the WSS scheme and sending an HTTPS request with websocket headers.
uri = Uri(
scheme: uri.isScheme("wss") ? "https" : "http",
userInfo: uri.userInfo,
host: uri.host,
port: uri.port,
path: uri.path,
query: uri.query,
fragment: uri.fragment);
Source: https://github.com/dart-lang/sdk/blob/aa793715e0f122cbd27cd8f9cc12201ff43c19b1/sdk/lib/_http/websocket_impl.dart#L1014 .

Related

axios POST get 400

This is driving me crazy!
Exactly the same POST request works fine in Insomina per screenshot below:
The only header Insomina has is: Content-Type: application/json.
Now, the same request in code (I even copied the code generated from Insomnia for axios) via axios in Typescript:
const saveReqConfig: AxiosRequestConfig = {
method: 'POST',
url: 'THE SAME URL USED IN Insomina',
timeout: 3000,
data: {
name: `TestName`,
uri: `TestURI`,
statusCode: '200',
simulatedLatency: '0',
contentType: "application/json",
tags: '',
response: 'testing...',
type: 'VA',
},
headers: {
'Content-Type': 'application/json',
}
}
const normalAxios = axios.create();
const test = await normalAxios.request(saveReqConfig);
Don't understand why I am getting AxiosError: Request failed with status code 400 from code but the same request works fine in Insomina.
I think you did not set the headers correctly or you may not have setup the .create() properly.
Something like this:
const instance = axios.create({
url: '/post',
baseURL: 'https://httpbin.org',
method: 'POST',
timeout: 1000,
headers: {
Content-Type: 'application/json' // <- set your headers
}
});
let res = await instance.request({ // <- pass the data here
data: { // This should be whatever you want to post to this url. I just copied what you had.
name: `TestName`,
uri: `TestURI`,
statusCode: '200',
simulatedLatency: '0',
tags: '',
response: 'testing...',
type: 'VA',
}
});
Are you sure you need to use the .create() factory? The normal post like this might suite your needs better?
const data= { title: 'Axios POST Request Example' };
const headers = {
Content-Type: 'application/json'
};
axios.post('url', data, { headers }).then(response => console.log(response.data.title);
Posting here in case it helps someone.
It turned out that I couldn't post the request programmatically is because of lack of a TLS certificate. I didn't know that Insomnia has the option to disable the TLS and that's why it works in Insomnia.
To disable TLS (Do NOT do this in production!) from node with axios, create an instance of axios with a https agent setting rejectedUnauthorized to false e.g.
const instance = axios.create({
httpsAgent: new https.Agent({
rejectedUnauthorized: false
})
});
Also, set the environment variable as:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

Cookies not sent with cross-origin-request

After days of searching and trying, I'm here now.
I deployed the React Application in Netlify and the Node.js backend in Heroku. Everything works fine in localhost environment. But after deploying, cookies are not sent in request header.
CORS:(Backend Node.js)
app.use(cors({
origin: CORS_ORIGIN,
credentials: true,
allowedHeaders: "Content-Type,Accept,User-Agent,Accept-Language,Access-Control-Allow-Origin,Access-Control-Allow-Credentials,cache-control"
}));
Axios:
import axios from "axios";
axios.defaults.withCredentials = true;
export default axios.create({
baseURL: process.env.REACT_APP_BACKEND + "/api",
headers: {
"Content-type": "application/json",
"Access-Control-Allow-Origin": process.env.REACT_APP_BACKEND,
},
});
Fetching Data(Mutation): apiClient is imported from above Axios.js and cookies is handled by react-cookies
apiClient.post("/auth/login",{ email: "name#mail.com", password: "pawspaws" })
.then((res) => {
setCookie("jwt", res.data.accessToken, { path: process.env.REACT_APP_PATH || "/", domain: process.env.REACT_APP_DOMAIN, maxAge: 26000, secure: true, sameSite: 'None' });
setCookie("refresh", res.data.refreshToken, { path: process.env.REACT_APP_PATH || "/", domain: process.env.REACT_APP_DOMAIN, maxAge: 2600000, secure: true, sameSite: 'None' });
setCookie("user", res.data.user, { path: process.env.REACT_APP_PATH || "/", domain: process.env.REACT_APP_DOMAIN, maxAge: 26000, secure: true, sameSite: 'None' });
}).catch((err) => console.log(err.response))
Above code sets the cookies.. and it's working.
Now, below is the request I'm sending which doesn't send the Cookies along with the request:
apiClient.get("/posts/timeline", { params: { email: "name#mail.com" } })
.then((res) => { console.log(res.data); })
.catch((err) => { console.log(err.response) });
Well, it returns unauthorized since the Cookie is not sent at all..
Ok, i found my own solution.. It was pretty easy.. It was setting up proxy
Just added line below to package.json in frontend:
"proxy":"https://random.name.herokuapp.com",
FYI, for Netlify, we need additional _redirects file in public folder.
_redirects
/api/* https://random.name.herokuapp.com/api/:splat 200
/* /index.html 200
In my case I had hardcoded my front end api calls to the herokubackend
axios.get("https://infinite-ocean-8435679.herokuapp.com/api/user")
First removed the hrokupart from the request like this
axios.get("/api/loguserin")
Then added the proxy value to the bottom of the package.json
"proxy":"https://infinite-ocean-8435679.herokuapp.com",
Next added a file called _redirects inside the react public folder.(_redirects is the file name and it has no extension such as .txt so don't add _redirects.txt )
Add the following inside _redirects file
/api/* https://infinite-ocean-8435679.herokuapp.com/api/:splat 200
/* /index.html 200
inside _redirects file formatting will be weird just add above code replacing heroku part with your backend url.
React automatically add all the files inside the public folder to its build folder once created.
deploy the site to Netlify

How to connect to web socket with APP_ID, APP_KEY and APP_SECRET with Flutter Application

How to connect to web socket with APP_ID, APP_KEY, and APP_SECRET with Flutter Application.
I used flutter_pusher_client and laravel_echo but I got `java.security.cert.CertPathValidatorException: Trust anchor for certification path not found error.
My Code
PusherOptions pusherOptions = PusherOptions(
encrypted: true,
host: 'socket.abcd.com',
cluster: 'mt1',
port: 6001,
);
FlutterPusher flutterPusher = FlutterPusher(
'PUSHER_APP_KEY',
pusherOptions,
enableLogging: true,
);
Echo echo = Echo({
'broadcaster': 'pusher',
'client': flutterPusher,
'wssHost': 'socket.abcd.com',
'wssPort': 6001,
'disableStats': true,
'forceTLS': true,
'autoConnect': true,
'enabledTransports': ['ws', 'wss'],
});
flutterPusher.connect(
onConnectionStateChange:
(FPC.ConnectionStateChange connectionStateChange) {
print(
'PUSHER CONNECTION STATE CHANGE C: ${connectionStateChange.previousState} -> ${connectionStateChange.currentState}',
);
},
onError: (FPC.ConnectionError connectionError) {
print(
'PUSHER CONNECTION ERROR C: ${connectionError.code} ${connectionError.exception} ${connectionError.message}');
},
);
echo.join('chat')
..here((user) => print('ECHO USER: user'))
..listen('NewMessage', (event) {
print('ECHO MESSAGE: $event');
});

rest-hapi standalone endpoint not returning handler results

Forgive me if it's a silly question, but the last time I coded in javascript was almost 20 years ago... I'm re-learning javascript these weeks and I'm not sure I got it all.
I'm using hapi with rest-hapi and want to add some standalone endpoints, basically translating the backend portion of this Autodesk tutorial form express.
I'm using the basic rest-hapi example main script, and tried to add a route with the following code:
//api/forge.js
module.exports = function(server, mongoose, logger) {
const Axios = require('axios')
const querystring = require('querystring')
const Boom = require('boom')
const FORGE_CLIENT_ID = process.env.FORGE_CLIENT_ID
const FORGE_CLIENT_SECRET = process.env.FORGE_CLIENT_SECRET
const AUTH_URL = 'https://developer.api.autodesk.com/authentication/v1/authenticate'
const oauthPublicHandler = async(request, h) => {
const Log = logger.bind('User Token')
try {
const response = await Axios({
method: 'POST',
url: AUTH_URL,
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
data: querystring.stringify({
client_id: FORGE_CLIENT_ID,
client_secret: FORGE_CLIENT_SECRET,
grant_type: 'client_credentials',
scope: 'viewables:read'
})
})
Log.note('Forge access token retrieved: ' + response.data.access_token)
return h.response(response.data).code(200)
} catch(err) {
if (!err.isBoom){
Log.error(err)
throw Boom.badImplementation(err)
} else {
throw err
}
}
}
server.route({
method: 'GET',
path: '/api/forge/oauth/public',
options: {
handler: oauthPublicHandler,
tags: [ 'api' ],
plugins: {
'hapi-swagger': {}
}
}
})
}
The code works and I can display the access_token in nodejs console, but swagger doesn't get the response:
At first I thought that an async function cannot be used as handler, but my hapi version is 17.4.0, and it supports async handlers.
What am I doing wrong?
It turns out it was an easy fix: I just needed to specify the Hapi server hostname in my main script!
The problem was with CORS, since Hapi used my machine name instead of localhost. Using
let server = Hapi.Server({
port: 8080,
host: 'localhost'
})
solved my problem.

Facebook crawler seems to trigger Forbidden errors on my ExpressJS app

I've noticed that everytime I use the Facebook debugger tool or the Facebook like button (set up using Addthis) ExpressJS ends up throwing Error: Forbidden (twice in a row).
So I assume the crawler sends a request that weirds out Express, maybe something in the headers like for this issue?
Here is the header sent by Facebook crawler:
{
host: 'runningheroes.co',
accept: '*/*',
'accept-encoding': 'deflate, gzip',
range: 'bytes=0-8999',
referer: 'http://runningheroes.co/',
'user-agent': 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)',
'x-forwarded-for': '173.252.100.117',
'x-forwarded-port': '80',
'x-forwarded-proto': 'http',
connection: 'keep-alive'
}
And here is my Express config:
app.configure(function(){
app.use(express.compress());
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('port', process.env.PORT || 8000);
app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
app.use(express.logger('dev'));
app.use(express.bodyParser({ keepExtensions: true }));
app.use(express.methodOverride());
app.use(express.cookieParser('secret'));
app.use(express.cookieSession({ secret: 'secret', cookie: { domain: '.runningheroes.co', maxAge: 1000*60*60*24, httpOnly: true } }));
app.use(app.router);
// Error handling:
app.use(function(err, req, res, next) {
if(!err) { return next(); }
// This is were the Forbidden errors are logged
logger.error('Express.error.middleware: ' + err);
res.redirect('/error');
});
});
Any help would be much appreciated.
PS: the debugger still succeed to parse the og meta tags and the like button works as well despite the errors.