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);
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
I am new to node express (started with node long time ago but didn't do much) and I would like to learn how to use it. I am going through some of my older work and reading lots of tutorials but I just can't seem to get this one working.
I have this app that reads data from some sensors on serial port and sends it to sesors.ejs. I would like to reprogram it in express. I have the sensor reading in terminal but not in ejs.
old (working) app.js
var http = require('http');
var fs = require('fs');
var url = require('url');
var path = require('path');
const { SerialPort } = require('serialport')
const { ByteLengthParser } = require('#serialport/parser-byte-length')
const port = new SerialPort({ path: 'COM4', baudRate: 9600 })
const parser = port.pipe(new ByteLengthParser({ length: 30 }))
var sensors = fs.readFileSync('views/sensors.ejs');
var app = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type':'text/html'});
res.end(sensors);
});
var io = require('socket.io').listen(app);
io.on('connection', function(data){
console.log
});
parser.on('data', function(data){
console.log(data.toString("UTF8"));
io.emit('data', data.toString("UTF8"))
});
app.listen(3000);
old (working) sensors.ejs
<script>
var socket = io();
socket.on('data', function(data){...}
</script>
This works great.
I went through several express routing tutorials but I don't know how to send io data to router.
I have c/p most of the code from old app.js to new sensor.js in routes dir, without fs, app.listen etc. I have c/p sensors.ejs to views folder.
In new app.js I have:
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var sensorsRouter = require('./routes/senzori');
var app = express();
app.set('views', path.join(\__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(\__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/senzori', sensorsRouter);
index.ejs and users.ejs (fetch mysql data) are working (express is installed and working)
Thanks
I have found the solution. If anyone else with my level of "knowledge" needs the solution, here it is:
I have moved reading serial port to bin/www
The only code in sensors.js is:
router.get('/', function(req, res, next) {
res.render('sensors');
});
I'm running a simple express server on my machine and attempting to ping it from a StackBlitz web container, but am getting the following error when trying to connect:
FetchError: request to https://192.168.1.23:8443/ failed, reason: connect ECONNREFUSED 192.168.1.23:8443
I've tried:
using https
allowing cors
setting up host: 0.0.0.0
Here's the code for the server, its a vanilla node project, just with express and cors.
var fs = require('fs');
var http = require('http');
var https = require('https');
var cors = require('cors')
var privateKey = fs.readFileSync('key.pem', 'utf8');
var certificate = fs.readFileSync('cert.pem', 'utf8');
var credentials = { key: privateKey, cert: certificate };
var express = require('express');
var app = express();
app.use(cors())
app.get('/', (_, res) => res.send(`hello`));
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
httpServer.listen(8080, '0.0.0.0');
httpsServer.listen(8443, '0.0.0.0');
Here is the code for the stackblitz container, it is a vanilla node project with node-fetch:
import fetch from 'node-fetch';
const url = 'https://192.168.1.23:8443/';
const response = await fetch(url)
.catch((err) => console.error(err));
console.log(response?.status || 'failed');
Try use a html page to connect to your server. If still error then try embed an iframe in your html.
My Zoho Catalyst framework isn't passing the request.body. Here is the code.
module.exports = (req, res1) => {
const debug = require('debug');
const https = require('https');
const tools = require('./tools.js');
const crypto = require('crypto');
const express = require('express');
const app = express();
app.use(express.json())
app.use(express.urlencoded({ extended: true }));
app.use(express.text());
function getHash(){
var hmac = crypto.createHmac('sha256', apisecretkey);
hmac.update(dataToSign);
return hmac.digest('base64');
};
var url = req.url;
switch (url) {
case '/scanName':
//var s = JSON.stringify(req.body)
console.log(req.body)
console.log(req.get('Accept'))
console.log(req.accepts('application/json'));
res1.write('xx')
res1.end()
break;
case '/':
Here is the output:
undefined
*/*
application/json
I've tried every form of POST from Postman that I can think of, and still nothing.
You have bound the express app variable to recognize the incoming data of the following types JSON, urlencoded and text. But you haven’t used that app variable to get the incoming request so technically it is like you have declared it but never used it. So, your function code couldn’t be able to identify the type of incoming data in the request body. You can modify your code like below:
'use strict';
const debug = require('debug');
const https = require('https');
const tools = require('./tools.js');
const crypto = require('crypto');
const express = require('express');
const app = express();
app.use(express.json());
app.use(express.text());
app.use(express.urlencoded({ extended: true }));
app.post('/scanName',async(req, res) => {
try {
let body = req.body;
console.log(body);
res.status(200).send(body);
} catch (error) {
console.log(error);
res.status(500).send(error);
}
});
module.exports = app;
You have to export the express app variable to make the endpoints accessible. You can check out this tutorial where we have shown an example of how to get and send data in the Catalyst Advanced IO function using Express.js.
The application is build in MEAN stack and we are able to run the port successfully in 3001 port and our web application is running perfectly in HTTPS ... Now we have build the ionic app for the same application where we are using the same back up..
The ionic app is not logging in or form is not getting submitted..
Do we need to use a seperate port for the same application to use for ionic like
ionic in 8001
and web application (Angular) in 3001
What is the procedure to run the ionic app in SSL (https)
Any suggestion will be great helpful and thank you in advance
My code is as follows which worked perfectly:
var express = require('express');
var DataController = require('./user/DataController');
var UserController = require('./user/UserController');
var db = require('./database/database-db');
var cors = require('cors');
var app = express();
app.use(cors());
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
// res.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
// res.setHeader("Access-Control-Allow-Origin", "http://localhost:8100");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.use('/user', UserController);
app.use('/data', DataController);
app.get('/', function(req, res){
res.send("Welcome to the secure mobile and web development world");
});
// This settings are for HTTPS, SSL web applications.
// var https = require("https");
// var fs = require("fs");
// var options = {
// key: fs.readFileSync("/home/path/ssl/keys/key.key"),
// cert: fs.readFileSync("/home/path/ssl/certs/crt.crt")
// };
// https.createServer(options,app).listen(3001);
// console.log('Welcome to the security world')
// This settings are only for HTTP sites
// var http = require("http");
// var fs = require("fs");
// http.createServer(app).listen(3001);
// console.log('Welcome to the security')
//This settings are for both HTTPS,HTTP SSL web applications.
var https = require("https");
var http = require("http");
var fs = require("fs");
var options = {
key: fs.readFileSync("/home/path/ssl/keys/key.key"),
cert: fs.readFileSync("/home/path/ssl/keys/crt.crt")
};
https.createServer(options,app).listen(3001);
console.log('Welcome to the security world')
http.createServer(app).listen(3002);
console.log('Welcome to the proxy world')
Since the last Postman update, I'm unable to get the response data in the console, from the request body that I'm sending to the endpoint.
Here's the code:
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', (req, res) => {
console.log(req.body);
res.send('OK');
});
app.listen(8080, () => console.log('App is listening! :)'));
Then I make a POST request using Postman putting data in the Body part, On the log I get "{}".
I have tested with cURL, and it works, that's why I suspect it is a problem with Postman.
Thank you for your time!
Using the code from the question, I am able to see the request body logged out to the console. This is using either the raw > application/json option or the x-www-form-urlencoded option the send the request.
In order to see data from the form-data option in Postman, I needed to add the multer module to the code.
let express = require('express');
let multer = require('multer');
let upload = multer();
let app = express();
let bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', upload.array(), (req, res) => {
console.log(req.body);
res.send('OK');
});
app.listen(8080, () => console.log('App is listening! :)'));
As you can see from the image below, this is writing the request body to the console.