Socket.io GET/POST 404 - javascript

I was searching for a similiar issue, but I still can't fix this problem. I'm working on a chat app in ReactJs, Node/Express, Mongoose and Socket.io. Everything works, db is working, server is running, so now I want to add socket. I'm trying to connect client side with server, but I get error (about every 2/3sec) POST/GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=N5PeKkf 404 (Not Found).
React:
const host = 'http:localhost:5000/api/rooms'
const [endpoint, setEndpoint] = useState('')
const {width,mobileWidth} = props;
useEffect(()=>{
setEndpoint(`${host}${props.location.pathname}`);
socket = io(endpoint);
const roomId = props.location.pathname.slice(1,props.location.pathname.length);
socket.emit('join', {roomId})
},[endpoint])
Node:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const socketIo = require("socket.io");
const http = require("http");
const HttpError = require('./models/http-error');
const roomsRouter = require('./routes/rooms-routes');
const usersRouter = require('./routes/users-routes');
const app = express();
mongoose
.connect(
`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}#cluster0-lnoai.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`
)
.then(() => {
app.listen(process.env.PORT || 5000);
})
.catch(err => {
console.log(err);
});
const server = http.createServer(app);
const io = socketIo(server);
app.use(bodyParser.json());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');
next();
});
io.on('connection',(socket)=>{
console.log('connected');
})
app.use('/api/rooms', roomsRouter);
app.use('/api/users', usersRouter);
app.use((req, res, next) => {
throw new HttpError('Route not found.', 404);
});
app.use((error, req, res, next) => {
if (res.headerSent) {
return next(error);
}
res.status(error.code || 500).json({
message: error.message || 'An uknown error occurres!',
errorCode: error.code || 500
});
});

Related

NodeJS using Express, Error: getaddrinfo ENOTFOUND https

I have test with different solution but still error. I ran my code (backend) on Heroku, and I tested it with Postman.
Error is show like this
Error: getaddrinfo ENOTFOUND https
This is the app.js
const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const paketRoutes = require('./routes/paket-routes')
const transaksiRoutes = require('./routes/transaksi-routes')
const laporanRoutes = require('./routes/laporan-routes')
const HttpError = require('./models/http-error')
const app = express()
const PORT = process.env.PORT || 5000
app.use(express.json())
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Request-With, Content-Type, Accept, Authorization')
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE')
next()
})
app.get('/', (req, res) => {
res.send('Halo')
})
app.use({
host:'ameera-laundry.herokuapp.com',
path:'/paket'
}, paketRoutes)
app.use('/transaksi',transaksiRoutes)
app.use('/laporan', laporanRoutes)
app.use((req, res, next) => {
const error = new HttpError('Could not find this route', 404)
throw error
})
app.use((error, req, res, next) => {
if(res.headerSent) {
return next(error)
}
res.status(error.code || 500)
res.json({message: error.message || 'an unknown error occured'})
})
mongoose
.connect('mongodb+srv://name:password#mern.tr8rx.mongodb.net/task?retryWrites=true&w=majority')
.then(() => {
app.listen(PORT)
})
.catch(err => {
console.log(err)
})
I test with 1 api using host and path, but still fail. Please help, I cant find another solution, Newbie here.
Thanks for the answer and solution, help me a lot.

Cross-Origin Request Cors in NodeJS

I want to fetch my NodeJS server, but I receive a Cross-Origin Request echec.
This is my index.js server :
const express = require('express')
if (process.env.NODE_ENV !== 'production') require('dotenv').config()
const routerIdeas = require('./routes/ideas')
const PORT = process.env.PORT || 5000
const app = express()
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
res.send(200)
next()
})
app.use('/api', routerIdeas)
app.listen(PORT, () => {
console.log(`Server is running on port : ${PORT}`)
})
I also tried with the npm CORS package but it's the same problem :
const express = require('express')
var cors = require('cors')
if (process.env.NODE_ENV !== 'production') require('dotenv').config()
const routerIdeas = require('./routes/ideas')
const PORT = process.env.PORT || 5000
const app = express()
app.use(cors())
app.use('/api', routerIdeas)
app.listen(PORT, () => {
console.log(`Server is running on port : ${PORT}`)
})
And this is my fetch by the React app :
useEffect(() => {
const getIdeas = async () => {
setIsLoading(true)
try {
const response = await fetch("https://localhost:3004/api/ideas")
const data = await response.json()
setIdeasArray(data)
setIsLoading(false)
} catch (err) {
console.error('getIdeas error: ', err, err.stack)
}
}
getIdeas()
}, [])
The browser's console always answer :
Blocking a Cross-Origin Request: the "Same Origin" policy does not allow viewing of the remote resource located at https://localhost:3004/api/ideas. Reason: CORS request failed.
Sorry, it was just a stupid error :
Wrong fetch URL => https://localhost:3004/api/ideas
Good fetch URL => http://localhost:3004/api/ideas
Why don't you use CORS node package (link)

How to catch POST request on back-end?

<!doctype html>
<head>
</head>
<body>
<script>
const Http = new XMLHttpRequest();
const url='http://localhost:4550/users';
Http.open("POST", url);
Http.send("hey");
Http.onreadystatechange = (e) => {
console.log(Http.responseText)
}
</script>
</body>
</html>
//user.js
var express = require('express');
var router = express.Router();
var array = [];
/* GET users listing. */
router.get('/', (req, res, next) => {
res.send('respond with a resource1');
});
router.post('/', (req, res, next) => {
res.send('respond with a resource2');
});
module.exports = router;
//app.js
const express = require('express')
const app = express();
app.get('/',(req,res)=> {
console.log('lior');
res.send('api running 2')});
app.use('/users',require('./routes/users'))
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
const PORT = process.env.PORT || 4550;
app.listen(PORT,()=> console.log('server started on port ${PORT}'));
I am new with connecting client and server side, and it might be why I couldn't find an answer for my question. Is a simple question.
As you can see I want to send "hey" from the client to the server(user.js). However I don't know how does I catch the response on the server side.
I know that a "hey" or neither the code make much sense, but is just an example to make things simple, I just wondering how does the server side could catch and handle the data.
Thanks in advance!
When you post data, specify how you are encoding it. It's generally best to use a standard encoding method rather than POSTing plain text. (Also don't start variable names with capital letters unless they are constructor functions)
const http = new XMLHttpRequest();
const url = 'http://localhost:4550/users';
const data = JSON.stringify({ value: "hey" });
http.open("POST", url);
http.setRequestHeader("Content-Type", "application/json");
http.send(data);
http.onreadystatechange = (e) => {
console.log(http.responseText)
}
Then in your server side code, use a body parser to decode the data.
Since you are using an absolute URL in the request, it seems likely that you are making a cross-origin request so you also need to grant permission using CORS.
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express()
const port = 4550
const jsonParser = bodyParser.json()
const corsOptions = {
origin: 'http://example.com',
optionsSuccessStatus: 200
};
const corsMiddleware = cors(corsOptions)
app.get('/', (req, res) => res.send('Hello World!'))
app.get('/users', (req, res, next) => {
res.send('respond with a resource1');
});
app.options("/users", corsMiddleware)
app.post('/users', corsMiddleware, jsonParser, (req, res, next) => {
// data is in `req.body` (which will have a `value` property because the object on the client does)
res.send('respond with a resource2');
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
(The above is untested and may have minor errors in it)
Please send serialized data as below:
const http = new XMLHttpRequest();
const url = 'http://localhost:4550/users';
const data = JSON.stringify("hey");
http.open("POST", url);
http.setRequestHeader("Content-Type", "application/json");
http.send(data);
You need to use bodyParser package
npm install body-parser
const bodyParser = require("body-parser");
and before setting up routes use it as below :
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Don't forget to allow the headers declaration as below :
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST"
);
next();
});
and now you can read your data as below
router.post('/users', (req, res, next) => {
console.log(req.body);
});

Exporting Objects in NodeJS for API

I'm trying to write a RESTful API in NodeJS that connects to a MySQL database. I have multiple files that handle routes:
I'm using the "mysql" package from www.npmjs.com. In app.js I create a connection object for the database but then want to use that object in both books.js and entries.js. I need to use the connection object to send queries to the database and I plan to do that in the routes files (books.js, etc.). What is the proper way to export and import that object? I'm new to NodeJS. Also, app.js is already exporting "app".
app.js:
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const bookRoutes = require('./api/routes/books');
const entryRoutes = require('./api/routes/entries');
const connection = mysql.createConnection({
host: 'localhost',
user: 'rlreader',
password: process.env.MYSQL_DB_PW,
database: 'books'
});
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'GET');
return res.status(200).json({});
}
next();
});
// Routes which should handle requests
app.use('/books', bookRoutes);
app.use('/entries', entryRoutes);
app.use((req, res, next) => { //request, response, next
const error = new Error('Not found');
error.status = 404;
next(error);
});
app.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message
}
});
});
module.exports = app;
books.js:
const express = require('express');
const router = express.Router();
const axios = require('axios');
router.get('/', (req, res, next) => {
axios.get('/').then(docs => {
res.status(200).json({
"hello": "hi"
})
}).catch(err => {
res.status(500).json({
error: err
});
})
});
module.exports = router;
GrafiCode had the answer to this one. I made a separate file called db.js
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'rlreader',
password: process.env.MYSQL_DB_PW,
database: 'books'
});
module.exports = connection;
Then, in books.js I added:
const con = require('../../db');
Then I was able to use the .query() from the mysql component in multiple files.

GET,HEAD response when making a passport Oauth github request

I keep getting
GET, HEAD
response, when authenticating github user. This application is using express, and react.
I tried many solutions when it comes to blocked by cors, and although some solutions that may work for some developers. None has work for me
for example a solution from another post, does not work.
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
Api call
router.get('/auth/github', passport.authenticate('github', { session: true, scope: ['profile'] }) );
router.get('/auth/github/callback',
passport.authenticate('github', { failureRedirect: '/' }),
function(req, res) {
// Successful authentication, redirect home.
var token = jwt.sign({ id: req.user.id}, 'nodeauthsecret');
res.cookie("jwt", token, { expires: new Date(Date.now() + 10*1000*60*60*24)});
res.redirect('http://127.0.0.1:8001/dashboard');
console.log(token)
console.log('this works');
});
app.js (express setup)
var express = require('express');
var app = express();
var userRoute = require('./routes/users');
var postRoute = require('./routes/posts');
var bodyParser = require('body-parser');
var logger = require('morgan');
var models = require('./models');
var User = require('./models/user');
var session = require('express-session');
var cookieParser = require('cookie-parser') ;
var cookieSession = require('cookie-session');
var dotenv = require('dotenv');
var env = dotenv.config();
var cors = require('cors');
const port = process.env.PORT || 8000;
const passport = require('passport');
const path = require('path');
const allowOrigin = process.env.ALLOW_ORIGIN || '*'
// CORS Middleware
if (!process.env.PORT) {
require('dotenv').config()
}
if (!process.env.PORT) {
console.log('[api][port] 8000 set as default')
console.log('[api][header] Access-Control-Allow-Origin: * set as default')
} else {
console.log('[api][node] Loaded ENV vars from .env file')
console.log(`[api][port] ${process.env.PORT}`)
console.log(`[api][header] Access-Control-Allow-Origin: ${process.env.ALLOW_ORIGIN}`)
}
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({
secret : 'nodeauthsecret',
resave: false,
saveUninitialized: true,
}));
// var corsOptions = {
// origin: 'http://example.com',
// optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
// }
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);
require('./config/passport-github')(passport);
app.use(function(req, res, next) {
res.locals.user = req.user; // This is the important line
console.log(res.locals.user);
next();
});
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
app.use('/api/users', userRoute)
app.use('/api/posts', postRoute )
app.listen(port, () => {
console.log('[api][listen] http://localhost:' + port)
})
Redux action
export const signWithGithub = () => {
return (dispatch) => {
Axios.get('localhost:8000/auth/github', {
headers: {
'content-type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Credentials': true
},
crossdomain: true
}).then( (res) => {
console.log(res);
dispatch({type: SIGN_GITHUB});
});
}
}
Home.js
signGithub = () => {
this.props.signWithGithub();
};
...
<a onClick={this.signGithub}>
<Chip
label="Sign In with Github"
clickable
avatar={< Avatar alt = "Natacha" src = "https://avatars0.githubusercontent.com/u/9919?s=280&v=4" />}
component="a"
className={classes.chip}/>
</a>

Categories