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.
Related
I have a React app (localhost:3000) and a Node app (localhost:3001) to run a simple system. The problem is I'm getting the error Access to XMLHttpRequest at 'localhost:3001/app' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
I have tried with app.use(cors()) and also with cors options as below. Still I'm getting the above error.
Node app.js
const express = require('express');
const app = express();
const cors = require('cors');
const corsOptions = {
origin: 'http://localhost:3000/',
credentials: true,
optionSuccessStatus: 200
}
app.use(cors(corsOptions));
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', "http://localhost:3000");
res.header('Access-Control-Allow-Headers', true);
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
next();
});
app.use(express.json());
app.get('/app', (req, res) => {
res.send({result: "hello"});
});
module.exports = app;
React app.js
import React, { Component } from "react";
import axios from 'axios';
class App extends Component {
componentDidMount(){ this.runInstance(); }
runInstance = () => {
axios.get(`localhost:3001/app`)
.then(res => {
console.log("res", res);
})
.catch(err => {
console.log("AXIOS ERROR:", err);
})
}
render() { return(<div></div>) }
}
export default App;
How can I solve this?
Since you use nodejs
installing cors
npm install cors
After that
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
Then after applying "cors" middleware. You need to insert "http://" before "localhost: in your react app".
Example
axios.get(`http://localhost:3001/api/app`)
.then(res => {
console.log("res", res);
})
.catch(err => {
console.log("AXIOS ERROR:", err);
})
You are using a different port to the one defined in corsOptions, try like below.
// app.js
...
runInstance = () => {
axios.get(`http://localhost:3000/app`)
.then(res => {
console.log("res", res);
})
.catch(err => {
console.log("AXIOS ERROR:", err);
})
}
...
Update:
Change all references to 3000 to be 3001, so that your CORS configuration matches the request you are trying to make.
const corsOptions = {
origin: 'http://localhost:3001/',
credentials: true,
optionSuccessStatus: 200
}
...
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', "http://localhost:3001");
...
});
I am developing the admin interface for my software and it was working fine in development (when I 'react start'). The problem is when I build and run it in production. React-admin won't load the data coming from the server, because of these 2 error in its requests.
OPTIONS http://localhost:3000/user?filter={}&range=[0,9]&sort=["id","ASC"] - CORS FAILED
GET http://localhost:3000/user?filter={}&range=[0,9]&sort=["id","ASC"] - NS_ERROR_DOM_BAD_URI
in development react-admin doesn't request 'options /user' neither I get these errors. I am using node express in the server side:
require('dotenv').config();
const express = require('express')
var cors = require('cors')
const app = express()
const port = process.env.SERVER_PORT;
const serverIp = process.env.SERVER_IP;
const { verifyUser } = require('./middleware/verification');
const { readUsers } = require('./db/dbManager');
app.use(cors())
app.get('/user', verifyAdmin, (req, res) => {
readUsers().then((response) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Expose-Headers', 'Content-Range');
res.setHeader('Content-Range', 'posts 0-24/319');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(response));
});
})
app.options('/user', verifyAdmin, (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Expose-Headers', 'Content-Range');
res.setHeader('Content-Range', 'posts 0-24/319');
res.setHeader('Content-Type', 'application/json');
res.end();
})
app.use(express.static('build'));
app.listen(port, () => {
console.log(`Example app listening at http://${serverIp}:${port}`)
});
How can I fix these errors I am having in production?
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)
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
});
});
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.