fetch api doesn't access to nodejs + express url - node.js

i have a server.js which has listening port 4000. Please check below code
const port = 4000;
const express = require('express')
const cors = require('cors')
const app = express()
const mysql = require('mysql');
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "musteri"
});
con.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});
app.use(cors());
app.use(express.urlencoded({ extended: false }));
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
app.get('/user', function(req, res, next) {
console.log(req);
con.query('select * from musteri_ayarlar', function (error, results, fields) {
if(error) throw error;
res.send(JSON.stringify(results));
});
});
app.listen(port, (err) => {
if(err) { console.log(err) };
console.log('Service Port ' + port + ' started')
})
with above code listening localhost:4000/user
i can access without any problem from chrome when i call localhost:4000/user that returns a record from mysql.
My problem started when i call localhost:4000/user adress from fetch api.
it saying POST http://localhost:4000/user 404 (Not Found)
Here is my fetch code from app.jsx
componentDidMount() {
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Access-Control-Allow-Origin':'*',
'Content-Type': 'applications/json'
},
body: JSON.stringify({ username: "John", password: 30 })
};
fetch(`http://localhost:4000/user`, requestOptions)
.then(handleResponse => handleResponse.text())
.then(user => {
console.log(user);
localStorage.setItem('user', JSON.stringify(user));
return user;
});
}```
What is wrong with my fetchAPI code? Thanks.

app.get('/user', function(req, res, next) {
console.log(req);
con.query('select * from musteri_ayarlar', function (error, results, fields) {
if(error) throw error;
res.send(JSON.stringify(results));
});
});
you have made an get endpoint here to access it
Change the request method in fetch
const requestOptions = {
method: 'GET',
headers: {
'Accept': 'application/json',
'Access-Control-Allow-Origin':'*',
'Content-Type': 'applications/json'
}
};
GET doesn't accept any body , as you are not using the request , this will satisfy

Related

XHR POST 404 error when using fetch api with NodeJS and Express

I am currently learning how to use the fetch api for my front-end. I continue to get the XHR 404 POST error.
//Backend file
const express = require("express");
const app = express();
require("dotenv");
const Port = process.env.PORT || 5000;
app.use(express.static("public"));
app.use(express.json());
app.use(
express.urlencoded({
extended: false,
})
);
const nodemailer = require("nodemailer");
const Mail = require("nodemailer/lib/mailer");
require("nodemailer-mailgun-transport");
app.use(express.json());
app.get("/", (req, res) => {
res.sendFile("/public");
res.sendFile("/public/js/mail.js");
});
app.listen(Port, (req, res) => {
console.log(`listening on port ${Port}`);
});
app.post("/email"),
(req, res) => {
FromMailjs = req.body;
console.log(FromMailjs);
const transporter = nodemailer.createTransport({
auth: {
user: process.env.Email,
pass: process.env.Pass,
},
});
const MailOptions = {
from: req.body.Email,
to: process.env.MyEmail,
text: `${req.body.FirstName}, ${req.body.LastName}
, ${req.body.PhoneNumber}, ${req.body.Email}`,
};
transporter.sendMail(MailOptions, (error, info) => {
if (error) {
console.log(error);
res.send("error");
} else {
console.log("Email sent");
res.send("success");
}
});
};
//Frontend file
const ContactForm = document.querySelector(".contact-form");
ContactForm.addEventListener("submit", (e) => {
e.preventDefault();
let FirstName = document.getElementById("Fname");
let LastName = document.getElementById("Lname");
let PhoneNumber = document.getElementById("PhoneNumber");
let Email = document.getElementById("Email");
const FormData = {
FirstName: FirstName.value,
LastName: LastName.value,
PhoneNumber: PhoneNumber.value,
Email: Email.value,
};
const PostOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(FormData),
};
console.log(FormData);
fetch("/email", PostOptions);
});
XHRPOSThttp://localhost:5000/email
[HTTP/1.1 404 Not Found 27ms]
I have tried changing the routes hoping that it was just a routing issue and I still get the same error. I was using XHR before fetch and I got the same 404 error. My front-end is receiving the correct information but I can't get my backend to receive the information.
You have a typo. Please use:
app.post("/email", (req, res) => {
Instead of:
app.post("/email"),
(req, res) => {

Can't make a successful Authorization request from Axios request to third-party API

I have been dealing with this issue where I am attempting to make a get request to a third-party API using Axios in my Node.js server. The endpoint requires a username and password which I am passing along as follows:
export const getStream = async(req, res) => {
let conn = createConnection(config);
let query = `SELECT * FROM cameras WHERE id = ${req.params.id}`
conn.connect();
conn.query(query, async (error, rows, _) => {
const camera = rows[0];
const {ip, user, pass} = camera;
if (error) {
return res.json({ "status": "failure", "error": error });
}
const tok = `${user}:${pass}`;
const userPass = Buffer.from(tok)
const base64data = userPass.toString('base64');
const basic = `Basic ${base64data}`;
const result = await axios({
method: 'get',
url: `<API URL>`,
headers: {
'Authorization': basic,
'Content-Type': 'multipart/x-mixed-replace; boundary=--myboundary'
},
auth: {username: user, password: pass}
})
res.json(result)
});
conn.end();
}
I am then calling this endpoint in my React front-end as such:
const getStream = async () => {
try {
const result = await publicRequest.get(`camera/getStream/${id}`)
console.log(result)
} catch (error) {
console.error(error)
}
}
Each time I make this request, my node server crashes and I get a 401 unauthorized error in my console. It appears that my Authorization header is not getting passed to the server even though everything else gets passed along as so.
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'multipart/x-mixed-replace; boundary=--myboundary',
'User-Agent': 'axios/0.26.1'
},
method: 'get',
url: '<url>',
auth: { username: '<username>', password: '<password>' },
data: undefined
For extra information, this is how my node server is setup
import express, { urlencoded, json } from 'express';
import userRoute from './routes/userRoute.js';
import cameraRoute from './routes/cameraRoute.js';
import cors from 'cors';
const app = express();
app.use(cors());
app.options('*', cors());
app.use(json())
app.use(urlencoded({ extended: true }));
app.use(express.static('public'));
app.use('/api/user', userRoute);
app.use('/api/camera', cameraRoute);
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
I have been working on this issue for several days and each time I try something new, I always get a 401 error, and the server crashes.
Any suggestions would be greatly appreciated.

gatsbyjs and expressjs Error 400 Bad Request while fetch

I have a small backend with ExpressJS that sends an email, I have deployed this backend on a Heroku site, I have tried it with postman and everything is ok, it works, but when I want to use it from my gatsby site, it throws a problem with cors, the gatsby site is running on my localhost.
ExpressJS code:
import dotenv from 'dotenv';
import express from 'express';
import nodemailer from 'nodemailer';
import cors from 'cors';
if (process.env.NODE_ENV !== 'production') {
dotenv.config();
}
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(cors());
const contactAddress = process.env.CONTACT_ADDRESS || '';
const mailer = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: process.env.GMAIL_ADDRESS,
pass: process.env.GMAIL_PASSWORD,
},
});
app.post('/contact', (req, res) => {
if (!req.body.from)
return res.status(400).json({ message: 'From is required' });
if (!req.body.message)
return res.status(400).json({ message: 'Message is required' });
mailer.sendMail(
{
from: req.body.from,
to: [contactAddress],
subject: 'Contact from API',
html: `<h3>${req.body.from}</h3><br>${req.body.message}`,
},
(err, info) => {
if (err) {
console.log(err);
return res.status(500).send(err);
}
res.status(200).json({ success: true });
}
);
});
app.listen(process.env.PORT || 8000);
console.log(`App running on port ${process.env.PORT || 8000}`);
Code on frontend that make the request:
const onSubmit = async (data: IFormInputs) => {
console.log(data);
const formData = new FormData();
Object.keys(data).forEach((el) => {
formData.append(el, data[el]);
});
try {
const res = await fetch(`${BACKEND_URL}contact`, {
method: 'POST',
body: formData,
});
console.log(res);
} catch (e) {
console.log(e);
}
}
I have also tried adding some configuration on the fetch, but it does not work anyways
const res = await fetch(`${BACKEND_URL}contact`, {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
},
referrerPolicy: 'origin',
body: formData,
});
The error throws the following error:
{
status: 400,
statusText: "Bad Request",
type: "cors",
ok: false,
}
I have searched similar questions on StackOverflow, but any of the solutions have worked for me.
The answer on this post does not work for me, because I don't have the backend and the frontend on localhost, I am consuming the API from my Heroku site.
Thanks in advance!
You are listening on the port 8000. Are you sure it's correct? Let's try on posts 8080.
You can also set headers:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});

React-native post data to Node Express server not working

I'm trying to post data in my bdd with my node express server from my react-native app but it's doesn't work, req.body is empty. (get data and display on my react-native application works by the way..)
When I do the request in my app, I got this in my server terminal :
Go to http://localhost:3000/users so you can see the data.
req.body : {}
Connected to bdd
1 record inserted, result : OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 71,
serverStatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
My react-native code :
fetch('http://localhost:3000/newuser', {
method : 'POST',
mode : 'no-cors',
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json',
},
body : JSON.stringify({
username : 'test',
})
}) .then((response) => response.json())
.catch((error) => {
console.error(error);
});
My node server :
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const cors = require('cors');
const connection = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database : 'react'
});
// Starting our app.
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/users', function (req, res) {
...
});
app.post('/newuser', function (req, res) {
// console.clear()
console.log("req.body : ", req.body)
let username = req.body.username;
connection.getConnection(function (err) {
if (err) throw new err;
console.log("Connected to bdd");
const sql = "INSERT INTO users(username) VALUES ('" + username + "')";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted, result : ", result);
res.send('POST request')
});
});
})
// Starting our server.
app.listen(3000, () => {
console.log('Go to http://localhost:3000/users so you can see the data.');
});

NextJS and React: Cannot read property 'email' of undefined

I try to send data from my client to my server. For that, i use React with NextJS, because you have the server and client-side in one app.
I use the following handleSubmitFunction:
handleSubmit() {
const email = this.state.email;
fetch('/', {
method: 'POST',
body: email,
});
}
and this is my server.js file in the located in / at my project
const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare()
.then(() => {
const server = express()
//parse application
server.use(bodyParser.urlencoded({ extended: false}))
//parse application/json
server.use(bodyParser.json())
server.post('/', (req, res) => {
console.log(req.body.email);
res.end("success!");
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(3000, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})
.catch((ex) => {
console.error(ex.stack)
process.exit(1)
})
When the handleSubmit Function is running, i get the following Output from the Server Console:
Cannot read property 'email' of undefined
Where exactly is my mistake?
I have little experience in node JS environments. I would be very grateful if you could show me concrete solutions. Thank you for your replies.
It seems you have to parse header and JSON.stringify the email.
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email:email}),
}).then((res)=> console.log('Worked'))

Resources