How can I fix this CORS with Socket.io? - html

I'm having trouble migrating my locally hosted chat application using Socket.io to my live cloud server. I am aware there are solutions out there, however, I cannot find anything that solves my problem.
I am receiving "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at.... (Reason: CORS request did not succeed)"
'''
const io = require('socket.io')(3000)
io.on('connection', socket => {
socket.on('new-user', name => {
users[socket.id] = name
socket.broadcast.emit('user-connected', name)
})
socket.on('send-chat-message', message => {
socket.broadcast.emit('chat-message', {message: message, name:
users[socket.id]})
})
socket.on('disconnect', () => {
socket.broadcast.emit('user-disconnected', users[socket.id])
delete users[socket.id]
})
})
Above is the server.js file.
const socket = io('<url>:3000')
const messageForm = document.getElementById('send-container')
const messageInput = document.getElementById('message-input')
const messageContainer = document.getElementById('message-container')
This is the script my app is using, the is replaced by mine, it just masked on here.
Things I have tried:
Setting headers using "Header set Access-Control-Allow-Origin" in my Apache & Nginx config
Changing the url on the script
Changing the ports
So far I've no luck, please help me!!

Try
// Allow all origins
io.origins('*');
source

Related

How to serve index.html file with Apollo Server?

I have this code in index.js:
const PORT = process.env.PORT || 5000;
server.listen(PORT).then({ url }) => {
console.log(`Server running at url: ${url}`);
});
In local development, when I went to localhost:5000 on my browser, I could test with the GraphQL playground.
Now, I just finished deploying with Heroku. When I go to my URL, I see:
GET query missing. I assume this happens because apollo is trying to open the GraphQL playground, but it is blocked in production mode.
How can I tell apollo to serve client/index.html instead?
Note: I tried putting index.html in the root directory as well, but nothing changed.
I saw in a tutorial video that the answer to this question in express is:
app.use(express.static('client'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client','index.html'));
});
I don't know how to do this in Apollo.
The standalone Apollo Server cannot be used for serving static files or exposing other endpoints. If you need this functionality, you need to use an HTTP framework like Express, Hapi or Koa and then use the appropriate Apollo Server integration.
Example using Express:
const server = new ApolloServer({ ... });
const app = express();
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
);

404 Error when making a POST request using fetch()

I am following this tutorial from Hakernoon to set up Node.js with MySQL using my machine as local server.
I am using a few different tools, but they don't seem to be a problem. I'm using:
Ubuntu 16.04
Node.js
MySQL Workbench (He uses Homebrew because his is a Mac)
MySQL
knex.js
Express
*(Ubuntu and Workbench are the only differences)
Summarizing,the whole tutorial works well except when I reach the part of 'Login'. Here, we build a form to enter the user name and password making a POST requests. Then, if everything is OK, it returns a 200 status, else shows a message saying the login failed. And here is the problems. Every time I try to log in (even when being sure the credentials are correct and knowing that that user is stored in the database) it tells me that the login fails.
Checking on the browser inspect tool, it shows a Fail to load resources: the server responded with a status of 404 (Not found). It also points out that the problems is in the fetch() function I use in my post function to make the POST requests.
I checked the documentation on fetch() but is does not clarify much. Also I tried to contact the author of the tutorial and I got no answer. What am I doing wrong with fetch to give me the 404 status?
Also, every time I create a new user (also a POST request), it does it with no problem and I can see it in the database in MySQLWorkbench.
This is the file (app.js) with the code to create users and login:
const CreateUser = document.querySelector('.CreateUser')
CreateUser.addEventListener('submit', (e) => {
e.preventDefault()
const username = CreateUser.querySelector('.username').value
const password = CreateUser.querySelector('.password').value
post('/createUser', { username, password })
})
const Login = document.querySelector('.Login')
Login.addEventListener('submit', (e) => {
e.preventDefault();
const username = Login.querySelector('.username').value
const password = Login.querySelector('.password').value
post('/login', {username, password})
.then(({status}) => {
if(status === 200)
alert('login success')
else
alert('login failed')
})
})
function post (path, data) {
return window.fetch(path, { <========= Here is where the browser shows the problem
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
}
***I am not posting the rest of the code to not make it too long, if more info is needed, let me know). Thanks!

Upload image URL to SFTP server using Cloud Function

I am working on a task that uploads image to SFTP server with Firebase Function. But the image source is not from my local computer but a http URL such as https://image.com/abc.jpg. I am using ssh2-sftp-client npm package. Currently I am using my mac both for client and server and it is working fine when I am accessing local file(/Users/shared/abc.jpeg) and uploading it to local server(/Uesrs/shared/sftp-server/abc.jpeg). But when I tried to have access to https://image.com/abc.jpg. and upload it to local server I got the error that says "ENOENT: no such file or directory/ ...". And below is my code
const functions = require('firebase-functions');
let Client = require('ssh2-sftp-client');
exports.sftpTest = functions.https.onRequest((request, response) => {
let sftp = new Client();
const config = {
host: '192.***.***.***',
port: '22',
username: '****',
password: '****'
}
let localFile = 'https://images.unsplash.com/photo-1487260211189-670c54da558d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=934&q=80';
let remoteFile = '/Users/Shared/unsplash.JPG';
sftp.connect(config)
.then(() => {
sftp.fastPut(localFile, remoteFile);
})
.catch(err => {
console.error(err.message);
});
});
My first time to have access to sftp server and anyone's advice will be much appreciated.
The method you are using from this library does not support usage in the way you are trying to set it up. the method fastPut usually is to upload local files to a remote server, I think you should use the fastGet method in order to download files from a remote server, however, please note that there are no notes that indicate that you can use these methods with the URL in the way you are trying to achieve.

#feathersjs/socketio-client connection timeout. Why?

I maked follow:
feathers g app # with socket and rest
feathers g service # todos & NeDB
npm start
and simple client for this. I copy code from documentation
https://docs.feathersjs.com/api/client/socketio.
const feathers = require('#feathersjs/feathers');
const socketio = require('#feathersjs/socketio-client');
const io = require('socket.io-client');
const socket = io('http://localhost:3030');
const app = feathers();
app.configure(socketio(socket));
app.service('todos')
.on('created', message => console.log('New message created', message));
app.service('todos').find().then(r => {
console.log(r)
}).catch(e => console.log('error',e))
app.service('todos').create({
title: 'A message from a REST client'
});
this client code get me timeout errors for find() and create() methods
But if I make POST request by CURL, I have onCreated message in console
Why I got errors on create() and find() calls?
UPDATE:
I maked git repo for easy reproduce this problem
https://github.com/tolyanor/feathersjs-error
UPDATE2:
I change autogenerated file src/app.js like in feathers example chat application https://github.com/feathersjs/feathers-chat/blob/master/src/app.js
Now I CAN call service method create on client, but CAN NOT receive onCreated message. So, this code
app.service('/todos')
.on('created', message => console.log('New todos created', message));
never calling
You are using a Feathers v3 client with a Feathers v2 server. Old clients will be backwards compatible with new servers but not the other way around. Follow the migration guide to upgrade your server or generate a new application using #feathersjs/cli (feathers --version on the command line should show v3.5.0 or later).

using data from JSON in NodeJS

Hello i just started learning Nodejs and made a local server as a start
then i saw that most nodejs apps have config and package files i couldnt find any info on how to do a simple one or use JSON files so i tried myself this is what i got so far
this is the server file
var http = require('http');
var json = require('./package');
var fs = require('fs');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(addr.port);
console.log('server listening at', addr.address + ':' + addr.port);
and this is the json file
{
"addr": {
"address":"http://127.0.0.1",
"port":"8081"
}
}
i know that it will work with json.address and json.port
but when i added "addr" i thought it would simplify things with addr.port
so in short an explanation would be generously accepted on why it wont/shouldnt work or what im doing wrong
First of you should have a look at some tutorials or introduction sites like:
https://www.w3schools.com/nodejs/default.asp
Second:
The package.json file is the main configuration file of your nodeJS application. Thats the config file that defines your start point of your application as well as all included modules. simply use npm init to create a default package.json file with basic information.
Third:
If you require a json into your application as you did in your example the JSON is included hierarchically. Wich means The object you required has an attribute addr which itself is a new object with an attribute address.
So the correct way to access your information is json.addr.address based on your object description
you could also do something like this:
var network = require('./settings').addr;
console.log("ip => " + network.address);
console.log("port => " + network.port);
You need to list the parent object. You have put addr.address and addr.port, this means you are directly trying to access the addr object, but the this object doesn't exist. Try doing json.addr.address and json.addr.port and it should work.
var http = require('http');
var json = require('./package');
var fs = require('fs');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(json.addr.port);
console.log('server listening at', json.addr.address + ':' + json.addr.port);