I'm trying to send a post request to a node server using axios, here's what I've done in react-js.
axios.post('http://localhost:5000', {
firstName: 'Finn',
lastName: 'Williams'
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
And here's what I've done in the server.
const express = require('express')
const app = express()
const port = 5000;
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
Every time I send the request, I get the following message in the console Access to XMLHttpRequest at 'http://localhost:5000/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
What should I do to fix that?
Install CORS npm package to configure your express HTTP server cors.
npm install cors
Then import CORS package in your express application file like that:
const express = require('express')
const cors = require('cors')
app.use(cors())
const app = express()
const port = 5000;
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
Then in your request code, you should to request with GET method. You are using axios.post() which does POST request. And that will response you with 404 because you don't have app.post('/') route handler in your application. So the code should look like this:
const express = require('express')
const cors = require('cors')
app.use(cors())
const app = express()
const port = 5000;
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.post('/', (req, res) => {
res.send(Hello ${req.body.firstName} ${req.body.lastName}!`)`;
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
You can install the cors
npm install cors --save
after that you can add this code on server file
var cors = require('cors')
app.use(cors()) // Use this after the variable declaration
You're not sending CORS headers on your responses, so the requests are denied. This can be easily solved by:
Run npm i cors
Change your code to
const express = require('express')
const cors = require('cors');
const app = express()
const port = 5000;
app.use(cors());
// all the other stuff
This error basically occurs because of a security mechanism that browsers implement called the same-origin policy. It prevents any cross-domain communication which may lead to cyber attacks like cross-site request forgery.
While we develop backend APIs for our frontend apps, we have to enable Cross-Origin Resource Sharing (CORS) in our backend server. To do that there are several libraries, the most common one is Cors package. Install it and use it in your server app as follows-
const express = require('express');
const app = express();
const port = 5000;
app.use(cors());
app.get('/', (req, res) => {
res.send('Hello World!')
})
Related
I'm building an application that includes react and nodejs in it..
It started yesterday, I saw that suddenly the server does not respond to the requests I sent through the axios package in reactjs..
The server just ignores.
I see that in the network window in dev tools a request to the server is sent but there is no response from the server..
I tried to put middleware in the application that will check if the server accepts sent requests:
app.use((req, res, next) => {
console.log(req.path);
next()
})
And I didn't see an answer.. it's so frustrating (I've been on this problem for two days now)
What am I doing wrong? The request is sent from an application because I see it through the network..
An important thing: I saw once that after a very long time the server received the request I sent to it.. I send a lot of requests to the server through the application, could there be an overload on the server? I don't know what to think anymore..
Also important: Sometimes the server answers my requests.. 50% of the time it returns an answer and 50% of the time it doesn't..
Server's code:
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const path = require("path")
const app = express();
require("dotenv").config();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const bodyParser = require('body-parser')
const jwt = require("jsonwebtoken")
const User = require("./model/userModel")
const io = new Server(server, {
cors: {
origin: 'http://localhost:3000'
}
});
app.use(cors());
app.use((req, res, next) => {
console.log(req.path);
next()
})
mongoose.connect(process.env.MONGO_URL).then(() => {
console.log("Database Connection Successfuly.")
}).catch(err => console.log(err.message));
server.listen(process.env.PORT, () => {
console.log(`Server Started on Port ${process.env.PORT}`);
})
I found the error while deploying the node app on the server. the index.js file code
const connectToDb = require("./DBconfig");
const express = require('express')
const router = express.Router();
var cors = require('cors');
connectToDb();
const app = express();
const port = process.env.PORT | 5000;
app.use(cors());
app.use(express.json());
connectToDb();
app.use( '/api/user' ,require('./routes/user') );
app.use( '/api/post' ,require('./routes/post') );
app.get('/', (req, res) => {
res.send('The site is start now')
})
if(process.env.NODE_ENV === "production"){
app.use(express.static("client/build"));
const path = require("path");
app.get("*",(req,res)=>{
res.sendFile(path.resolve(__dirname,'client','build','index.html'))
})
}
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
when I deploy the app and install the node in the server like how I install the node in server I attached the picture in which I show the installation of the node. and above I add the index.js code. It works properly in the local machine but if I hit the URL of backend backendURL it show the service unavailable error message kindly give me the solution to solve this problem.
The app works fine on GET requests. But on a POST request with body an application error occurs. I can't figure out this problem.
My app setup using express is like this:
const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
require('dotenv').config()
const port = process.env.PORT || 5000
const app = express()
app.use(cors())
app.use(express.json())
app.get('/', (req, res) => {
res.send('Express Server Running...✔')
})
app.listen(port, () => {
console.log('Listening to port', port);
})
I'm trying to read messages from users via WhatsApp api with ultramsg
and use NGROK
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const PORT = 4000
app.use(bodyParser.json())
app.listen(PORT, () => console.log(`Server running ${PORT}`))
ngrok show display 404 error
You need Setup a webhook route
app.use(bodyParser.json())
app.post('/test_webhook', (req, res) => {
console.log(req.body)
res.status(200).end()
})
Now Webhook URL is : http://your_ngrok_url/test_webhook
I am unable to link my frontend(React) and backend(Nodejs) together with Axios as it keeps encountering Network Error (I have also included CORS into my backend application but it still does not work). The backend runs on Postman too but not when integrated with the frontend. Frontend is running at localhost:3000 while backend runs at localhost:5000
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:83)
Here is what my code looks like:
Frontend:
axios.get("http://localhost:5000")
.then((res) => {
console.log(res.data);
alert("Hi succeedd");
})
.catch((err) => {
console.error(err);
alert("Try again");
});
Backend:
const express = require("express");
const connectDB = require("./config/db");
var cors = require("cors");
const app = express();
app.use(cors({ origin: true, credentials: true }));
//Connect to database
connectDB();
//Init middleware to read data sent in req.body
app.use(express.json({ extended: false }));
app.get("/", (req, res) => res.send("API running"));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on ${PORT}`));
have you set up proxy in your package.json correctly?
you should add this line: "proxy": "http://localhost:5000" so that the it knows to proxy requests between a local frontend and backend
see this for more details: https://www.twilio.com/blog/react-app-with-node-js-server-proxy