Unable to fetch request in react(client-side) and express server - node.js

Iam trying to fetch request from backend in form of post and it seems like my backend and frontend are not serving together
React SignIn code(Client-side)
onSubmitSignIn=()=>{
fetch('http://localhost:3000/signin',{
method:"POST",
headers:{'Content-Type':'application/json'},
body: JSON.stringify({
email:this.state.signInEmail,
password:this.state.signInPassword
})
})
.then(response=>response.json())
.then(data=>{
if(data==='success'){
this.props.OnRouteChange('home');
}
})
}
Server side
const express = require('express');
const bodyparser= require('body-parser');
const cors = require('cors');
const app=express();
app.use(bodyparser.json());
app.use(cors());
app.post('/signin', (req,res)=>{
if(req.body.email===database.users[0].email && req.body.password===database.users[0].password){
res.json('success');
}
else{
res.status(400).json("error");
}
})
PS:Reactapp is running on port 3001 and server on port 3000.
also when i try signing in the request is in form of get method although i am using post method

Related

My nodejs server can't see my requests that I send in reactjs with axios

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}`);
})

CORS POST request blocked in EXPRESS & REACT on hosting & domain

I'm using express CORS module & react AXIOS on my host & domain.
I defined CORS() in my route middleware, and the GET request worked perfectly.
but for POST & PUT requests still, the Access-Control-Allow-Origin BLOCKED error displays.
ALSO I'm using webpack and dev server to proxy front end react
This is my express server.js file
const express = require("express");
const app = express();
const db = require("./config/db");
db.connect(() => {
console.log(`Postgres connected`);
});
// Middlewares
// CORS
const cors = require("cors");
app.use(cors(
{
origin: http://asia-sarmaye.ir
}));
// BodyParsing
var bodyParser = require("body-parser");
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// Router
app.use("/api", cors(), require("./routes/dum"));
// Listening
const port = 4000;
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
And this is REACT axios POST request
axios
.post(
"http://api.asia-sarmaye.ir/api/user",
{
headers: { "Access-Control-Allow-Origin": "*" }
},
data,
res => {
console.log(res.data);
}
)
any idea how to fix this?
You need to set proxy.
Hope below given link help you. It helped me too.
Enable CORS in my React App with Node.js backend

Nodejs app loops continuously and doesnot load the page, as well as cant send post request using postman

I am trying to create an api and send post request using the postman,
but for some reason I'm not getting the data which is sent through the
post man. Instead when I cancel the postman send request I get
response which is shown in the screenshot.
Postman Screenshot:
nodejs server response screenshot:
server.js
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
// importing custom created modules
const config = require('./config');
// Instantiating express
const app = express();
// Connecting to the mongodbLab
mongoose.connect(config.database, { useNewUrlParser: true }, (error) => {
if (error) {
console.log('Error :',error);
} else {
console.log('Connected to the database.');
}
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));
app.use(cors);
const userRoutes = require('./routes/account');
app.use('/api/accounts', userRoutes);
// Running the server at port 3000
app.listen(config.port, error => {
console.log('Server started with config file at Port: ' + config.port);
});
account.js
const router = require('express').Router();
const jwt = require('jsonwebtoken'); // Encrypts user data.
router.post('/signup', (req, res, next) => {
console.log(req.body);
});
module.exports = router;
I tried even changing from https://localhost:3000 to
http://localhost:3000 as suggested in this post Here
And even tried adding res.end() as suggested here and here.
But nothing is working, If I goto localhost:3000 the server just keeps loading infinitely. Please help!
Okay I got the solution, it was because of app.use(cors). I don't know why but when I commented out this line everything started to work perfectly.
But in the response although I get the json object. But there is an array of Object, which I didn't get.
Here's the response screenshot:
Edit:
I finally got it I didn't call the cors() method properly. It should have been app.use(cors()), but I called it as just app.use(cors) missing paranthesis().
Now Everything is working fine.

NodeJs unable catch the data post from ReactJs form

I using ReactJs build the form for user key in the details. I also using NodeJs to handle the post data from the React. But the NodeJs seem like did not catched the data.
This is react event handling
handleSave(e){
let caseData=this.state.caseInfo
let url = 'http://localhost:8080'
console.log(caseData)
fetch(url,{
method:"POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data: JSON.stringify({caseInfo: caseData}),
})
}
This is NodeJS
var http = require('http');
var url = require('url');
var bodyParser = require('body-parser')
var express = require('express')
var app = express()
http.createServer(function(req,res){
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
app.use(function (req, res){
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
console.log(JSON.stringify(req.body));
})
}).listen(8080);
I expect the data from the React can using post method to the Node and display the data in console log. However in the console of the server it display nothing.
It seems like you're not using express in the standard way. I'd change it to be more like the following...
app.use(bodyParser.json());
app.post('/', (req, res) => {
res.json({ posted: req.body });
console.log(JSON.stringify(req.body));
});
app.listen(8080);
And probably just get rid of the call to http.createServer altogether.
--
Check out the docs for more routing examples: https://expressjs.com/en/starter/basic-routing.html
If you are serving your react app from another server, for instance localhost:3000 (as used by create react app), and you are trying to make api calls to a server on localhost:8080 you are going to get CORS errors because the browser sees these as two different domains. To get started, you can look at the docs here: https://expressjs.com/en/resources/middleware/cors.html
But you will probably have to npm install cors where your server lives and use something like the following:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.use(bodyParser.json());
app.post('/', (req, res) => {
res.json({ posted: req.body });
console.log(JSON.stringify(req.body));
});
app.listen(8080);

Post request sent by CURL gets parsed correctly but when sent from postman, I get undefined data

I am learning Node.js as a result I am setting up a authentication service. I have an issue parsing the body from post request.
This is my index.js file
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const db = require('./queries')
const port = 3000
app.use(express.json());
app.use(bodyParser.json())
app.use(
bodyParser.urlencoded({
extended: true,
})
)
app.get('/', (request, response) => {
response.json({ info: 'Node.js, Express, and Postgres API' })
})
app.post('/login',function(req,res){
var username=req.body.username;
var password=req.body.password;
console.log("User name = "+username+", password is "+password);
res.end("yes");
});
This is printed on the console:
bash-3.2$ node index.js
App running on port 3000.
Username = undefined, password is undefined
But when i use CURL
curl --data "username=Jerry&password=jerry#example.com" http://localhost:3000/login
It works. Don't know why?
You have to change the postman header settings. Try changing the header content type value to application/json and change body to raw.

Resources