I have one Javascript file linked to HTML and that js file is calculating an array on clicking submit button in Html and I want to get that data to node js file on post route without displaying it in HTML page. How should I do that?
Your nodeJS program is running on a server, which could just be your computer if you are using localhost, which means that it is in not connected to your HTML page. Therefore, you need to send the data from your js file via fetch request. In your nodeJS file, you need a route for receiving that data, which you create using express.
const express = require("express");
const {json} = require("body-parser");
const app = express();
app.post("/submitData", (req, res) => {
const data = req.body;
console.log(data);
res.status(200).json({"Message": "Data posted", data});
})
app.listen(3000,() => {
console.log("Server running on port 3000");
})
Now, in your javascript file, you need a fetch request.
fetch(http://localhost:3000/submitData, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).then(response => {
return response.json();
}).then(data => {
console.log(data)
})
This should do the trick. I would also suggest you download Postman, which is great for testing APIs and trying out http requests
I forgot to point out, after doing:
const app = express();
you should put:
app.use(json());
I apologise for the mistake, it should remove the error you mentioned in the comment.
Related
i am sending a post request from fetch but the nodejs server is not able to access the body from the post request. I tried req.body but it just returns empty brackets.
const express = require('express');
const bodyParser=require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: true}))
app.use(bodyParser.json());
app.use(express.json());
app.get("/user",function(req,res){
res.send("just Checking");
});
app.post("/user", (req, res) => {
console.log(req.body);
res.send("got the data");
});
app.listen(3000,function(res){
console.log("server is workig a t local host 3000");
});
This is the browser side code
const checking = { name:"badmintion" }
function yo (){
fetch("/user",{
method : "POST",
Headers : {
'Content-Type':'application/json'
},
body: JSON.stringify(checking)
})
}
yo();
In the browser i can see that the data is being sent but i am unable to recieve the in the nodejs server it just shows empty brackets.
Edit: I was able to recreate the server code locally on my machine. I didn't find any issues. I used Postman to send the JSON to the /user route. The issue you might be having is in the front end.
Headers should be lowercase. You have capitalized it:
...
fetch("/user",{
method : "POST",
headers : {
...
}
...
Make sure you're sending data in a JSON format so that express can parse it into object:
To avoid any conflict for (parse json) better that remove body parser completely and try again.
For request, according to stanley, headers set as lowercase. Its will be work.
This tutorial maybe help u:
https://www.geeksforgeeks.org/express-js-express-json-function/amp/
I am building a small website using LiveScore api from rapidapi.com. How can I hide my api key when deploying my application. Tried .env method, serverless methods but didn't do much help. I am trying the api hiding method for the first time. Maybe that's why I am not getting it. Is there any method to hide api key which is fairly simple but a decent hiding?
//index.js
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'xxxxxxxxxx',
'X-RapidAPI-Host': 'livescore6.p.rapidapi.com'
}
};
fetch('https://livescore6.p.rapidapi.com/matches/v2/list-by-date?
Category=soccer&Date=20231801&Timezone=-7', options)
.then(
response => {
response.json().then(
data => {
//my code here
})
In plain client side Javascript there is not much you can do to hide API Keys. I took a quick glance at the RapidAPI docs and also this blog post from them, but they just use the API Keys as-is without securing anything. (lol)
So if you're worried about that information leaking, I would recommend you to create a backend in any backend language you prefer (it could be NodeJS, if you want to use Javascript) and use it as a proxy to make a request to that LiveScore API. If you do this you don't have to hardcode the API Keys in your client code, you could use dotenv in your backend, also you could control which endpoints to use and even add some custom basic authentication to be able to make a request.
This is a basic example using NodeJS and express:
const express = require('express');
const fetch = require('node-fetch');
const cors = require('cors');
const app = express();
app.use(express.json());
app.use(cors());
app.get('/api/livescore', async (req, res) => {
try {
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': process.env.RAPID_API_KEY,
'X-RapidAPI-Host': process.env.RAPID_API_HOST
}
};
const rapidApiResponse = await fetch('https://some-rapid-api-endpoint.com', options);
const parsedResponse = await rapidApiResponse.json();
return res.json({ data: parsedResponse });
} catch (err) {
return res.status(500).json({ err: err.message });
}
});
app.listen(process.env.PORT || 3000);
I looked up my problem and found this Express res.render is not rendering the page none of the answers helped and none of the others on google worked. I am trying to push a post request with a button that renders a partial ejs file to the screen. It will later get deleted and replaced when i add another button but that is a task for next time. No error is given. The client console.log works and the server console.log works.
here is my server js
const { request } = require('express')
const express = require('express')
const app = express()
app.set('view engine','ejs')
app.use(express.static('public'))
app.use(express.json({limit: '1mb'}))
app.get('/',(req,res)=>{
res.render('layout')
})
app.post('/',async(req,res)=>{
try {
res.render('./partials/hi')
} catch (error) {
console.log(error)
}
})
app.listen(5000,()=>{
console.log('server listening')
})
here is my main js (vanilla js)
const button = document.getElementById('button')
button.addEventListener('click',()=>{
// const hi = document.createElement(<%-require('../views/partials/hi.ejs')%>)
// document.appendChild(hi)
console.log('no')
const options = {
method : 'POST',
}
fetch('/', options)
})
here is the zip file (safe)
https://drive.google.com/file/d/1Vwu7VDv613hRKFCZQhBNbONaT4Dk_0x1/view?usp=sharing
The answer is it isnt possible guys
backend should only send data and dosent send pages that well why is ejs a thing i dont know but i wasnt going to work how i wanted to use it the answer is to build api and html separte and learn fetch and use it to call api and loop through api data
I want to send the variable from javascript to node js
here I am storing some data in my javascript variable
var roomurl = "this is the data";
And here is my nodejs code
app.post("/newcall", function(req, res) {
var n = (req.body.roomurl);
console.log("val"+ n);
});
I have included all the dependencies like express and body parser
but I am not how to send it
can I get help in my javascript code or
any Url from where I can get to now about how do
I send data from java script to node js ?
thanks
Actually, you should run the node/express application to a specific port, ex 3000
app.listen(3000, () => {
console.log('App running at 3000')
})
Then from your client you should post your data via Fetch API or another http client like this
fetch('http://localhost:3000/newcall', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({roomurl})
});
what is the correct way to use NodeJs with React?
Currently what I am doing is running Node on port 3000 and React on port 3001
Now, I my Node I have this route
app.get("/", (req, res) => {
console.log(req.user)
res.json(req.user)
})
Here console.log shows user details when I manually go to localhost:3000 but If I make an axios request from my react to the above given url it shows undefined.
componentWillMount() {
axios.get("http://localhost:3000/").then(response => {
console.log(response)
}).catch(error => {
console.log(error)
})
}
Now, The req.user is something which were getting from passport google Stratergy and I since the log from localhost:3000 shows the data and the log from localhost:3001 does not show data.
I am confused if I am using the node correct way? i.e sending in request via axios and getting data via res.json
Also, since most of the tutorial or the tutorial I followed used EJS instead of React where user mostly did res.render
I just wanted to know the equivalence of res.render for react in NodeJS
[Update:] I am enabling cross origin resource sharing via plugin in google chrome
EDIT: In discussion with OP I found out that this is most likely a passport authentication middleware related issue. Original answer follows.
Looks like a CORS issue, as your frontend providing server is on port 3001, and backend on 3000. I can show you the way I'm using it (in react+node CORS setup, although the issue has nothing to do with React) and I have no CORS issues:
On frontend I use native browser's fetch:
const fetchRelative = async (path, options) => {
const url = new URL('http://localhost:3000/' + path);
return await ((await fetch(url, options)).json());
};
Here async/await syntax is used. I'm using babel for transpile, but maybe browsers support that natively.
Options provided to fetch are for example:
{
method: 'POST',
body: JSON.stringify(order),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
};
For a simple get request you can leave the options parameter empty.
On backend (node+koa server) I use this:
const Koa = require('koa');
const koaBody = require('koa-body');
const cors = require('koa-cors');
const startServer = (port) => {
const server = new Koa();
server.use(cors({ origin: '*', allowMethods: ['GET', 'POST', 'DELETE', 'PUT', 'OPTIONS'] }));
server.use(koaBody());
server.use(bindRoutes());
server.listen(port);
};
Basically the same is for express server (https://expressjs.com/en/resources/middleware/cors.html).
bindRoutes is just koa-router configuration extracted in a separate file:
const Router = require('koa-router');
const bindRoutes = () => {
const router = new Router();
router.get('restaurants', async (ctx) => {
ctx.body = 'abc;
});
return router.routes();
};
CORS plugin is not used here.
P.S.
async/await explaination and Browser support status
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
fetch explaination and Browser support status
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
You can run both your Node server and React app on different ports and proxy the React app back to your Node server. This can be done without a CORS plugin. More details on how to set this up is here: https://medium.freecodecamp.org/how-to-make-create-react-app-work-with-a-node-backend-api-7c5c48acb1b0