Unable to Connect to Backend

Viewed 231

Hello i am Trying to connect React-Native with Node.js using Fetch Api i tried many solutions i tried putting my IP address,localhost and 10.0.2.2 but nothing works i dont get any response back but when i change my code a little bit it gives me network failed request error.

React-Native Code:

//Sending Request to Node.js using Fetch API
        await fetch("http://10.0.2.2:3000/studentSignup", {

            //Setting Method
            method:"POST",

            //Setting Headers
            headers:{

                //Setting Content-Type
                "Content-Type" : "application/json"
            },
            //Stringifying the email and password and storing it into body
            body:JSON.stringify({
                name,
                gmail,
                password,
                retype
            })
        }).then(res=>{
            console.log(res);
        }).catch(err=>{
            console.log(err);
        });

Node.js:

const express = require("express");
const app = express();

app.use("/studentSignup", (req,res,next)=>{
    console.log("ok");
});

app.listen(3000);
2 Answers

lots of Mistakes

Full source code

var express = require('express')
var cors = require('cors')
var app = express()
var bodyParser = require('body-parser')

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.use(jsonParser)
app.use(urlencodedParser)
app.use(cors())

app.post("/studentSignup", (req,res,next)=>{
    console.log("ok");
});

app.listen(3000);

First of all, it's app.post not app.use

app.post("/studentSignup", (req,res,next)=>{
    console.log("ok");
});

This might me due to cors

You can use this npm package to encounter this error cors

install cors in server folder

npm i cors --save

Usage

var express = require('express')
var cors = require('cors')
var app = express()
 
app.use(cors())
 
app.post("/studentSignup", (req,res,next)=>{
    console.log("ok");
});

app.listen(3000);

Use body parser to handle incoming data from frontend

install body-parser in server folder

npm i body-parser --save

Usage

var express = require('express')
var cors = require('cors')
var app = express()
var bodyParser = require('body-parser')

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.use(jsonParser)
app.use(urlencodedParser)
app.use(cors())

app.post("/studentSignup", (req,res,next)=>{
    console.log("ok");
});

app.listen(3000);

So i was debugging and i thought that i have 2 ip's first one was Internet's ip and the second one was mine pc's ip and i was using internet's ip instead of my machine's ip so i changed the ip and that worked smoothly.

Related