I have a web service and a node project with a html page. I want to sends get request from my node project to my web service and in the return of web service i want to print that "hello world" on my website.
My web service.
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("myresource")
public class MyResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "Hello World";
}
}
My Node project:
var express=require('express');
var http = require('http');
var https = require("https");
var request=require("request");
var app=express();
app.get('/',function(req,res){
res.sendfile('index.html');
});
app.listen(3000,function(){
console.log("Express Started on Port 3000");
});
app.get('/this',function(req,res){
request
.get('http://localhost:8080/ConnectingToNode/webapi/myresource')
.on('response', function(response) {
console.log(response.statusCode); // 200
console.log(response.headers['content-type']);
var a=response.toString();
console.log(a);
});
});
module.exports = app;
My index.html
<!DOCTYPE html>
<html>
<head>
<title>TO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
function This(){
window.open("http://localhost:8080/ConnectingToNode/webapi/myresource");
}
</script>
<button onclick="This()" type="button">Click Me!</button>
</body>
</html>
Related
im trying to implement a chat client, i think my client server communication work, because i receive the messages in different tabs. im using a https connection
im getting in chrome following error:
WebSocket connection to 'wss://localhost/socket.io/?EIO=4&transport=websocket&sid=B-vRFkxNxHPkiK6cAAAE' failed: websocket.js:54
in firefox:
Firefox can’t establish a connection to the server at wss://localhost/socket.io/?EIO=4&transport=websocket&sid=vSwzZh9BE3cpHZHPAAAC.
im using a self signed certificate, that i created with openssl, thats why i get follwing konsole log in chrome:
This site does not have a valid SSL certificate! Without SSL, your site's and visitors' data is vulnerable to theft and tampering. Get a valid SSL certificate before releasing your website to the public.
server.js:
const express= require('express')
const app= express();
const https= require('https')
const fs=require('fs')
const PORT=process.env.PORT || 443
const httpsOptions={
key: fs.readFileSync('cert/key.pem'),
cert: fs.readFileSync('cert/cert.pem')
}
var server=https.createServer(httpsOptions,app);
server.listen(PORT,function(){
console.log(`listening to port ${PORT}`)
})
const io = require('socket.io')(server,{maxHttpBufferSize:1e8}).listen(server)
app.get('/test', (req,res)=>{
res.sendStatus(200);
})
app.use(express.static(__dirname + '/public'))
app.use(require('./routes/posts'));
app.use(require('./routes/users'));
//app.use(require('./public/client'));
app.get('/',(req,res)=>{
res.sendFile(__dirname + '/login_register/login.html')
})
app.get('/register',(req,res)=>{
res.sendFile(__dirname + '/login_register/register.html')
})
app.get('/chatroom',(req,res)=>{
res.sendFile(__dirname + '/index.html')
})
io.on('connection',(socket)=>{
console.log('new connection',socket.id)
socket.on('message', (msg)=>{
socket.broadcast.emit('message',msg)
})
socket.on('file-message', (msg)=>{
socket.broadcast.emit('file-message',msg)
})
})
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="/style.css">
<script src="https://cdn.socket.io/4.4.1/socket.io.min.js" integrity="sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H" crossorigin="anonymous"></script>
</head>
<body>
<section class="chat_section">
<div class="brand">
<img src="" alt="">
<h1> chat</h1>
</div>
<div class="message_area">
</div>
<div>
<textarea id="textarea" cols="30" rows="1" placeholder="write a message "></textarea>
</div>
<input type="file"id="fileupload" name="fileName">
<button id="submitFile" onclick="submitData()">senden</button>
</section>
<script>
socket = io('https://localhost:443/')
//also testet:
//const socket=io()
//didnt worked
let userName;
let userName_;
//const textarea = document.getElementById('textarea')
let textarea=document.querySelector('#textarea')
let messageArea= document.querySelector('.message_area')
let file__ = document.querySelector('#fileupload')
userName=sessionStorage.getItem('displayUsername')
userName_= userName
console.log(userName_)
sessionStorage.removeItem('displayUsername');
sessionStorage.clear();
//console.log(userName_)
if(userName_==null){
alert("dont scam")
window.location.href = '/'
}
//console.log(localStorage.getItem(displayUsername));
textarea.addEventListener('keyup', (e)=>{
if(e.key === 'Enter'){
sendMessage(e.target.value)
}
})
function sendMessage(message){
let msg= {
user:userName_,
message:message.trim()
}
//append message to frontend call function
appendMessage(msg,'outgoing')
textarea.value=""
scrollBottom()
//send to server
socket.emit('message', msg)
}
function appendMessage(msg,type,isFile){
//dont needed to understand
}
//recive messages
socket.on('message',(msg)=>{
//console.log(msg)
appendMessage(msg,'incoming')
scrollBottom()
})
socket.on('file-message',(msg)=>{
console.log(msg)
//File name Here
let message={
message: msg.filename,
user: msg.user,
result: msg.result
}
//send to the others
appendMessage(message,'incoming',isFile=true)
})
function scrollBottom(){
messageArea.scrollTop=messageArea.scrollHeight
}
function submitData(){
//dont needed to understand
}
}
function downloadFile(result,filename){
//dont needed to understand
}
</script>
</body>
</html>
I'm trying to get an url with selenium and node.js, but when the site has an alert I can't accept it on Internet Explorer.
index.js
require('iedriver');
const express = require('express');
const webdriver = require('selenium-webdriver');
let ie = require('selenium-webdriver/ie');
function start(params) {
start_server();
let options = new ie.Options();
options.ignoreZoomSetting(true);
let driver = new webdriver.Builder()
.forBrowser('internet explorer')
.withCapabilities(options)
.build();
let site="http://127.0.0.1:3000/";
driver.get(site)
.then(()=>{
return driver.wait(webdriver.until.alertIsPresent(),10000)
.then(()=>{
let alert = driver.switchTo().alert();
return alert.accept()
console.log("go on");
})
})
;
}
const start_server=()=>{
const app = express();
const PORT = 3000;
app.use(express.static('static'));
app.get('/', function(req, res){
let options = {
root: path.join(__dirname+"/../static/")
};
let fileName = 'index.html';
res.sendFile(fileName, options, function (err) {
if (err) {
log(err);
} else {
console.log('Sent:', fileName);
}
});
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
};
start();
The site to open has an alert when page is loading, like this:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="loading.js"></script>
<title>Document</title>
</head>
<body>
</body>
</html>
loading.js
alert("accept before start");
This has to work on Internet Explorer.
When running , after 5 minutes it shows this
UnhandledPromiseRejectionWarning: TimeoutError: Timed out waiting for page to load.
at Object.throwDecodedError (C:\d\adhoc\node\copyimgwz\node_modules\selenium-webdriver\lib\error.js:517:15)
at parseHttpResponse (C:\d\adhoc\node\copyimgwz\node_modules\selenium-webdriver\lib\http.js:642:13)
and stops like this
blocking alert on ie with selenium
Please, any idea how to accept that alert with selenium?
EDIT
I found out a solution, adding this line it's already working fine
options.introduceFlakinessByIgnoringProtectedModeSettings(true);
I was able to make it work, adding this line
options.introduceFlakinessByIgnoringProtectedModeSettings(true);
in this section
let options = new ie.Options();
options.ignoreZoomSetting(true);
options.introduceFlakinessByIgnoringProtectedModeSettings(true);
Aparently, On internet explorer you need to activate this characteristic to let you work.
Hello I am trying to learn how to connect a server to a website page. I have made my server in node.js and attempted to use the ws library. I'm not sure what to do on the client side. On the documentation page on ws (https://www.npmjs.com/package/ws#simple-server) it says I have to use "require" to import ws, however i'm assuming that you need to use node.js to use a "require" statement which I am not on my client.
Any tips or links to information is appreciated
// Server
const fs = require('fs');
const https = require('https');
const WebSocket = require('ws');
const path = require('path');
const server = https.createServer({
cert: fs.readFileSync(path.join(__dirname, 'cert', 'cert.pem')),
key: fs.readFileSync(path.join(__dirname, 'cert', 'key.pem'))
});
const wss = new WebSocket.Server({server})
console.log(server)
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
server.listen(443, function () {
console.log('Server is listening on 443');
});
// html page --------------------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const ws = new WebSocket("wss://websiteName.com");
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function incoming(data) {
console.log(data);
});
</script>
</body>
</html>
Android app does not connect via socket.io, but via browser everything is fine. If I access via browser http://localhost:3000, it works, but when I run the android app nothing happens and there is no error message either. Note: I am using nodejs.
MainActivity.java
package com.security.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;
public class MainActivity extends AppCompatActivity {
public Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//I created a ddns domain for external access directing to the nodejs
server port 3000
try {
socket = IO.socket("http://my_domain_ddns:3000");
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
node.js
const express = require('express');
const path = require('path');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'public'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use('/', (req, res) => {
res.render('index.html');
});
io.on('connection', socket => {
console.log(`Socket conectado: ${socket.id}`);
});
server.listen(3000);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="with=device-with, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Chat</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.1.3/socket.io.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form id="chat">
<input type="text" name="username" placeholder="Digite seu usuario">
<div class="messages"></div>
<input type="text" name="message" placeholder="Digite sua mensagem">
<button type="submit">Enviar</button>
</form>
<!-- Fazendo a conexao do front com o socket -->
<script type="text/javascript">
var socket = io('http://my_domain_ddns:3000');
</script>
</body>
</html>
I have corrected the url in index.html
var socket = io('http://my_domain_ddns:3000');
Change localhost in your android by the public IP of your router.
Do a port forwarding from your router to your server.
Check that your server has the port where you do your forwarding is open.
This video video give more explanation.
Well, I found another way that worked.
private void initiateSocketConnection() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(SERVER_PATH).build();
webSocket = client.newWebSocket(request, new SocketListener());
}
build.grade
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
I am trying to send some json object from the server side to the client side.
var express = require('express');
var app = express();
var server = app.listen(1337);
var io = require('socket.io').listen(server);
var json = {
var1: 1,
var2: 2,
var3: 3,
};
io.on('connection', function(json) {
io.send('message', json);
});
app.listen(3000);
and on index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('message', function(data) {
console.log(data);
});
</script>
</body>
</html>
I keep getting this error
Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?
EIO=2&transport=polling&t=1602487581123-0' from origin 'null' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested resource.
Use "socket.io": "^2.3.0", for server side, change server side code to following:
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var json = {
var1: 1,
var2: 2,
var3: 3,
};
io.on('connection', function() {
io.send('message', json);
});
http.listen(3000, () => console.log('HTTP server is listening on port 3000'));
For the CORS header, any origins being allowed by default.
And I recommend you use the latest version of socket.io for the client-side. You can use this CDN.
client side:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.1/socket.io.js" integrity="sha512-AcZyhRP/tbAEsXCCGlziPun5iFvcSUpEz2jKkx0blkYKbxU81F+iq8FURwPn1sYFeksJ+sDDrI5XujsqSobWdQ==" crossorigin="anonymous"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('message', function(data, json) {
console.log(data, json);
});
</script>
</body>
</html>
Create HTTP Server for client-side:
☁ 64313396 [master] ⚡ http-server -p 3001
Starting up http-server, serving ./public
Available on:
http://127.0.0.1:3001
http://172.31.160.227:3001
http://10.23.128.81:3001
The output of browser console: