0

Below is my code and I am unable to figure out why I get >net::ERR_CONNECTION_REFUSED TypeError: Failed to fetch

 const signup=(user)=>{
        // console.log(name,email,password);

        fetch(`${API}/signup`,{
            //we can write whatever we are gonna send to backend here
            method:"POST",
            mode:'cors',
            headers:{
                "Content-Type": "application/json",
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Request-Method": "*",
                Accept: "application/json",
            },
            body:JSON.stringify(user)
        })
        .then(response=>{
            return response.json()
        })
        .catch(err=>{
            console.log(err)
        });
    };

This is my Request Headers from network ** Provisional headers are shown Accept: application/json Access-Control-Allow-Origin: * Content-Type: application/json DNT: 1 Referer: http://localhost:3000/ sec-ch-ua: "Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99" sec-ch-ua-mobile: ?0 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36 **

Here's my APP.js, i have added cors package at the last and also implemented it the last, have a look into it too.

require('dotenv').config() //allows us to use the env variables in the main file.
const express =require('express'); //express is used to configure routes 
const mongoose=require('mongoose');
const morgan=require('morgan'); //used as middleware
const bodyParser=require('body-parser');
const cookieParser=require('cookie-parser');
const expressValidator=require('express-validator');
const cors=require('cors'); //providing a Connect/Express middleware that can be used to enable CORS with various options.

//import routes
const authRoutes=require('./Routes/Auth');
const userRoutes=require('./Routes/User');
const categoryRoutes=require('./Routes/Category');
const productRoutes=require('./Routes/Product');

//app
const app=express();


//db
mongoose.connect(process.env.DATABASE,{
    useNewUrlParser:true,
    UseCreateIndex:true
}).then(()=>console.log("Database Connected"));


//middleware
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(expressValidator());
app.use(cors());


//routes
app.use("/api",authRoutes);
app.use("/api",userRoutes);
app.use("/api",categoryRoutes);
app.use("/api",productRoutes);


const port=process.env.PORT || 8000

app.listen(port,()=>{
    console.log(`Server is running on port ${port}`);
})

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Mehul
  • 1
  • 2
  • I believe you'd want Accept to be quoted. Not that I think it would help with your problem, but still you're referring to a variable name. – agiopnl Aug 31 '22 at 05:19

1 Answers1

0

In Cross Domains, Unless server have cors support, Client cannot make requests to that server. So we should have the server configuration.-By @Vishnu

Try to add below line also in the headers

Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"

If it doesn't work try to use cors in app

import cors from 'cors';
app.use(cors);

OR

var 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");
  next();
});
Syed Mohib Uddin
  • 718
  • 7
  • 16