I am trying to write a code in NodeJS to make the websocket connection.
I send the following to create a new websocket connection
For Example:
wsLocation: ws://127.0.0.1:80/poll/31
wsProtocol:protocol1
wsCookie: -http-session-=41::http.session::9f9a4a003ae3088647ef019f789d753d;
But unable to make a websocket connection. I tried the below 4 formats
// Request1
// const ws = new WebSocket(wsLocation, wsProtocol, {
// headers: {
// Cookie: wsCookie,
// },
// });
// Request2
// const ws = new WebSocket(wsLocation, wsProtocol, {
// headers: {
// ["Cookie"]: wsCookie,
// },
// });
// Request3
// const ws = new WebSocket(wsLocation, wsProtocol, {
// headers: {
// ["Set-Cookie"]: wsCookie,
// },
// });
// Request4
// const ws = new WebSocket(wsLocation, wsProtocol, {
// headers: {
// "Set-Cookie": wsCookie,
// },
// });
None of them are working.
What is wrong in my request?
Related
In the following code, you can see that I am creating an errorLink. It makes use of an observable, a subscriber and then it uses this forward() function.
Can someone explain to me what's exactly happening here. I am bit familiar with observables, but I cannot understand what's going on here.
When creating the observable, where does the observer argument come from?
I would love to dive a bit deeper.
Also, why is bind used, when creating the subscriber?
const errorLink = onError(
({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
for (let err of graphQLErrors) {
switch (err.extensions.code) {
case "FORBIDDEN":
console.log("errs!")
// ignore 401 error for a refresh request
if (operation.operationName === "RehydrateTokens") return
const observable = new Observable<FetchResult<Record<string, any>>>(
(observer) => {
console.log(observer)
// used an annonymous function for using an async function
;(async () => {
try {
console.log("yop bin hier")
const accessToken = await refreshToken()
console.log("AT!", accessToken)
if (!accessToken) {
throw new GraphQLError("Empty AccessToken")
}
// Retry the failed request
const subscriber = {
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
}
forward(operation).subscribe(subscriber)
} catch (err) {
observer.error(err)
}
})()
}
)
return observable
}
}
}
if (networkError) console.log(`[Network error]: ${networkError}`)
}
)
Just so that you are understanding the context.
Iam combining mutliple apollo links.
const httpLink = createHttpLink({
uri: "http://localhost:3000/graphql",
})
// Returns accesstoken if opoeration is not a refresh token request
function returnTokenDependingOnOperation(operation: GraphQLRequest) {
if (isRefreshRequest(operation)) {
return localStorage.getItem("refreshToken")
} else return localStorage.getItem("accessToken")
}
const authLink = setContext((operation, { headers }) => {
let token = returnTokenDependingOnOperation(operation)
console.log("tk!!!", token)
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
},
}
})
const client = new ApolloClient({
link: ApolloLink.from([errorLink, authLink, httpLink]),
cache: new InMemoryCache(),
})
simple website contact submit code using fetch sending formdata to api.
the fetch method returns'Failed to execute 'fetch' on 'Window': Invalid name' error in console, meanwhile XMLHttpRequest works.
How can i fix the fetch method?
contactForm.addEventListener('submit', async function (e) {
e.preventDefault();
// console.log('clicked');
const formData = {
name: formName.value,
email: formEmail.value,
tel: formTel.value,
message: formMessage.value,
};
// FIXME
try {
const response = await fetch('/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData),
});
return response.json();
} catch (err) {
console.log(err.message);
}
// XMLHttp methode works
// let xhr = new XMLHttpRequest();
// xhr.open('POST', '/');
// xhr.setRequestHeader('Content-Type', 'application/json');
// xhr.onload = function () {
// if (xhr.responseText === 'success') {
// //add a popout window
// formName.value = '';
// formEmail.value = '';
// formTel.value = '';
// message.value = '';
// } else {
// alert('Something went wrong!');
// }
// };
// xhr.send(JSON.stringify(formData));
});
I have a spring boot + angularjs application, i configured it to have a socket connection. this is my socket controller in angularjs:
function SocketController($timeout, localStorageService) {
var vm = this;
var accessToken = localStorageService.get('accessToken');
var stompClient;
// i can see valid value of token in console
console.log(accessToken)
if (accessToken) {
var socket = new SockJS('/looping',
null,
{
transports: ['xhr-streaming'],
headers: {'Authorization': 'Bearer ' + accessToken}
});
stompClient = Stomp.over(socket);
stompClient.connect({"X-Authorization": "Bearer " + accessToken}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/loops', function (message) {
console.log(message);
});
});
} else {
console.log("token expired");
}
function sendEvent(loopId, value) {
if (stompClient != null) {
stompClient.send("/topic/loops", {}, JSON.stringify({'loopId': new Date(), 'value': 'hey silver'}));
}
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
stompClient = null;
}
console.log("Disconnected");
}
}
now, the problem is that when i check request headers in firefox devtools, authorization header doesn't set as you can see below:
How can i solve this problem? I'm new to socket.
UPDATE
When i edited the request using firefox devtools and set Authorization header in request headers, received response with 200 status code but the response content in html of index.html !
I wrote the below code to assign session attributes from my application,
var lexruntime = new AWS.LexRuntime();
var params = {
botAlias: 'PizzaOrder', /* required */
botName: 'PizzaOrder', /* required */
inputText: 'profile list', /* required */
userId: '160728846416', /* required */
sessionAttributes: {
//'<token>': cookies['token'],
'token': cookies['token'],
'communityid':cookies['communityid'],
'selectedAuthorId':cookies['selectedAuthorId'],
'kfurl':cookies['kfurl']
/* '<String>': ... */
}
};
//console.log("Cookies in index js "+cookies['token']);
lexruntime.postText(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
I want to access the session attributes in my lambda function using intentRequest.sessionAttributes.seesionattributename in the below code and as shown below
function GetAuthors2(intentRequest,callback) {
const token2 = String(intentRequest.sessionAttributes.token);
const communityid2 = String(intentRequest.sessionAttributes.communityid);
// --------- http start ---------
var options = {
hostname: 'kf6-stage.rit.albany.edu',
port: 443,
path: '/api/communities/'+communityid2+'/authors',
headers: {
'Content-Type' : "application/json",
'Authorization' : "bearer " + token2
}
};
https.get(options, (resp) => {
console.log("#in Http");
let data2 = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data2 += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
var data_2 = JSON.parse(data2);
const cList2 = [];
data_2.forEach(function(i){
cList2.push(i.firstName);
});
callback(close(intentRequest.sessionAttributes, 'Fulfilled',
{
contentType: "PlainText or SSML",
content: "Hi,You have "+cList2.length+" authors registered Bharghav. Here is the list \n"+ cList2.join()
}
));
});
});
}
but after the intent request I am getting the following response "Sorry, I was unable to process your message. Try again later."
If I hardcode the values in the lambda function it works fine.
Can someone kindly tell me where am I doing wrong in accessing the session attributes??
This worked for me. accessing the session attributes from the event/input. Then accessing the attribute by name.
exports.handler = async (event) => {
var attributes = event['sessionAttributes'];
console.log('attrs; ',attributes);
let sessValue;
if( attributes != null)
sessValue = attributes['fileName'];
AWS recently launched API gateway with sockets and it can proxy to lambda. In my observation AWS api socket is completely wss so I have done custom connect setting which is there in the code section. lambda and other setting I learned tested with wscat successfully as described in this link -
https://hackernoon.com/websockets-api-gateway-9d4aca493d39
But on integration with socket.io in browser it just keeps on reconnecting after 18-19 Seconds and connect is never fired! lambda and api gateway timeout is 30 Seconds which I think can be ignored as it doesn't interrupt the connection with wscat for 4-5 minutes.
I am new to sockets and the code in comments shows failed tries. Also tried googling but couldn't find much about AWS API socket and Socket.io. So any guidance or support is appreciated
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
</head>
<script>
socket = io(
`wss://abcd.execute-api.us-east-1.amazonaws.com/prod`
, {
path: `/prod/`,
forceNew: true,
// autoConnect: false,
// reconnection: false,
upgrade: true,
transports: ['websocket',
'polling',
'flashsocket'
]
});
socket.on('connect', function () {
socket.emit({"action":'message',"data":"hello return"}, () => {
console.log("message Sent");
});
});
// socket.emit({"action":'message',"data":"hello return"}, () => {
// console.log("message"); // true
// });
// socket.on('message', () => {
// console.log("message"); // true
// });
// socket.on("connection", function (socket) {
// console.log("connection")
// })
// socket.on('connect', () => {
// console.log("connect"); // true
// });
// socket.on('connected', () => {
// console.log("connected"); // true
// });
// socket.on('open', () => {
// console.log("open"); // true
// });
// socket.on('disconnect', (reason) => {
// console.log("disconnect->",reason);
// // if (reason === 'io server disconnect') {
// // // the disconnection was initiated by the server, you need to reconnect manually
// // socket.connect();
// // }
// // else the socket will automatically try to reconnect
// });
// socket.on('close', (reason) => {
// console.log("close->",reason);
// // if (reason === 'io server disconnect') {
// // // the disconnection was initiated by the server, you need to reconnect manually
// // socket.connect();
// // }
// // else the socket will automatically try to reconnect
// });
// // socket.open();
// // console.log(socket);
// socket.on( (res) => {
// console.log("res", res);
// });
// socket.on('reconnect', (attemptNumber) => {
// console.log("reconnected", attemptNumber); // true
// });
// socket.on('reconnecting', (attemptNumber) => {
// console.log("reconnecting...", attemptNumber); // true
// });
// socket.on('reconnect_error', (error) => {
// console.log("reconnect_error",error);
// });
// socket.on('reconnect_attempt', (error) => {
// console.log("reconnect_attempt->", error)
// // socket.io.opts.transports = ['polling', 'websocket'];
// });
// socket.on('error', (error) => {
// console.log("error->", error);
// });
// socket.on('ping', () => {
// console.log("ping");
// });
// socket.on('pong', () => {
// console.log("ping");
// });
</script>
</html>
I tested below Code in vue2 in Nuxt + Vuetify, I wanted to post for vue3 but I am still trying to get this done in little time I get after day Job. Any corrections are welcome. Thanks
export default {
data() {
return {
socketconnection: {},
listenersStarted: false,
}
},
created() {
this.onLoad()
this.notificationDialog()
this.startListeners()
this.$on('serverSelected', (server) => {
console.log('ran from $on server--', server)
const message = {
text: server,
right: false,
ts: new Date()
}
this.$store.commit('setMessage', message, { root: true })
})
},
methods: {
onLoad() {
try {
if (!localStorage.getItem('_t')) { return true }
if (this.socketconnection === true) {
console.log('socket already there... reconn unrequried!')
return true
}
const token = localStorage.getItem('_t')
const wsUri = `wss://test.example.com/prod?token=${token}`
const websocket = new WebSocket(wsUri)
websocket.onopen = (evt) => {
this.socketconnection = true
}
websocket.onclose = (evt) => { this.onClose(evt) }
websocket.onmessage = (evt) => { this.onMessage(evt) }
websocket.onerror = (evt) => { this.onError(evt) }
} catch (e) { console.log(e) }
},
onClose(evt) {
this.socketconnection = false
console.log('socket closed reconnecting...', evt)
this.onLoad()
},
onMessage(evt) {
console.log('evt---', evt)
this.$emit('serverSelected', evt.data)
},
onError(evt) {
console.log(evt)
},
}
}