Get value from client side script and override server side script - javascript

Below are my server side and client side JavaScript files. I have hard coded queryObject in server side script I can display the body in client-side.
The problem is how to get value from client side for queryObject variable in server side and override the existing values.
In short, current program converts USD to GBP as I hard-coded it. I want a way to access queryObject from client side and give my own values.
//=====================Server Side Script========================//
var request = require('request');
const path = require("path");
const express = require("express");
const app = express();
// const hbs = require("hbs");
const port = process.env.PORT || 3000;
const pathPublic = path.join(__dirname, "../public");
const pathView = path.join(__dirname, "../templates/views");
app.set("view engine", "hbs");
app.set("views", pathView);
app.use(express.static(pathPublic));
app.get("", (req, res) => {
res.render("home", {
title: "Currency Converter"
});
});
app.get("/currency", (req, res) => {
const uri = "https://currency-exchange.p.rapidapi.com/exchange?",
headers={
'x-rapidapi-host': 'currency-exchange.p.rapidapi.com',
'x-rapidapi-key': 'b13c4f3d67msh8143a7f1298de7bp1e8586jsn4453f885a4e7'
}
const queryObject = {
q: 1,
from: 'USD',
to: 'GBP'
};
request({
url:uri,
qs:queryObject,
headers: headers
},
function (error, response, body) {
if (error) {
console.log('error:', error); // Print the error if one occurred
} else if(response && body) {
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
res.json({'body': body}); // Print JSON response.
}
})
});
app.listen(port, () => {
console.log("Server is running on port " + port);
});
//=====================Client Side Script========================//
const currency = document.querySelector("#currency");
const text1= document.querySelector(".text1");
const text2= document.querySelector(".text2");
const text3= document.querySelector(".text3");
const Form = document.querySelector("form");
function refreshPage() {
window.location.reload();
}
Form.addEventListener("submit", e => {
e.preventDefault();
fetch("http://localhost:3000/currency").then(response => {
response.json().then(data => {
if (data.error) {
console.log(data.error);
} else {
currency.textContent = data.body;
}
});
});

SOLUTION:
In order to modify any values in server, you have to send appropriate HTTP method (eg: POST) with appropriate data in it. And let the server handle the request to change the content of object to make an API call from there.
I made some changes in your code for demonstration and install 'cors', 'body-parser' module and other missing modules to make it run.
HTML:
<!DOCTYPE html>
<html>
<body>
<div id="currencyType">
<select id="fromCurrency">
<option value="USD">USD</option>
<option value="GBP">GBP</option>
</select>
<select id="toCurrency">
<option value="USD">USD</option>
<option value="GBP">GBP</option>
</select>
</div>
<button type="button" id="getCurrency">Get Currency</button>
<div id="currency" name="currency" type="text"></div>
<script>
const currency = document.querySelector("#currency");
const btn = document.getElementById("getCurrency");
function refreshPage() {
window.location.reload();
}
btn.addEventListener("click", e => {
var fromCurrency = document.getElementById("fromCurrency");
fromCurrency = fromCurrency.options[fromCurrency.selectedIndex].value;
var toCurrency = document.getElementById("toCurrency");
toCurrency = toCurrency.options[toCurrency.selectedIndex].value;
var data = {
fromCurrency: fromCurrency,
toCurrency: toCurrency
};
// calls the API with POST method with data in it
fetch("http://localhost:3000/currency", {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
}).then(response => {
response.json().then(data => {
if (data.error) {
console.log(data.error);
} else {
currency.textContent = "1 " + fromCurrency + " = " + data.body + " " + toCurrency;
}
});
});
});
</script>
</body>
</html>
NodeJS:
var request = require('request');
const path = require("path");
const express = require("express");
const app = express();
var cors = require('cors')
// const hbs = require("hbs");
var bodyParser = require('body-parser');
const port = process.env.PORT || 3000;
const pathPublic = path.join(__dirname, "public");
const pathView = path.join(__dirname, "templates/views");
app.set("view engine", "hbs");
app.set("views", pathView);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(pathPublic));
app.use(cors())
app.get("", (req, res) => {
res.render("home", {
title: "Currency Converter"
});
});
app.post("/currency", (req, res) => {
console.log(req.body);
const uri = "https://currency-exchange.p.rapidapi.com/exchange?",
headers={
'x-rapidapi-host': 'currency-exchange.p.rapidapi.com',
'x-rapidapi-key': 'b13c4f3d67msh8143a7f1298de7bp1e8586jsn4453f885a4e7'
}
const queryObject = {
q: 1,
from: req.body.fromCurrency,
to: req.body.toCurrency
};
console.log(queryObject);
request({
url:uri,
qs:queryObject,
headers: headers
}, function (error, response, body) {
if (error) {
console.log('error:', error); // Print the error if one occurred
} else if(response && body) {
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
res.json({'body': body}); // Print JSON response.
}
})
});
app.listen(port, () => {
console.log("Server is running on port " + port);
});
Sample output:

You'll code in client-side to send a request to server-side containing the query object.
And on the server-side, you pick up your query object.
There are so many ways of doing this.
Using a GET request with parameters - On the server-side your query object will be available at res.query.params
Using a POST request - On the server side you will want to use the body-parser plugin for parsing your response body and hence, your data will be available at res.body
Read on body parser

Related

{"error":"invalid_client"} client credentials error spotify with express

I am developping an api on spotify.
I want to retrieve clients credentials. I set up my app on the dashboard.
My client_id and secret are correct.
But I have the same error at the end when I try to retrieve this client credential: "error":"invalid_client"
I look for my problem on web but no one correspond to my problem.
Here is my code:
`
const express = require("express");
const path = require("path");
const cors = require("cors");
const fetch = (...args) =>
import('node-fetch').then(({default: fetch}) => fetch(...args));
const request = "https://accounts.spotify.com/api/token";
const code = Buffer.from(client_id + ":" + client_secret).toString("base64");
const app = express();
const optionsTOKEN = {
method: "POST",
body: "grant_type=client_credentials",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic" +code
},
// json: true,
};
app.get("/code", async (req, res) => {
const data = await retrieveCode(request, optionsTOKEN);
console.log(res.statusCode)
res.send(data);
});
app.listen(8888, () => {
console.log("server running on port 8888");
});
async function retrieveCode(URlRequest, options) {
try {
const res = await fetch(URlRequest, options);
console.log(res);
const data = await res.json();
console.log("la data vaut" + data);
return data
} catch (err) {
console.log(`L'erreur: ${err}`);
}
}
`
Thank you for your help
I try to modify the parameters in my options, set up a new project on my dahsboard, change my port.
I am expecting to retrieve the access token
You needs to add a space between "Basic" and code
before
"Basic" +code
After
"Basic " +code
#1 With this code
This full test code with hide client_id and client_secret
const express = require("express");
const fetch = (...args) =>
import('node-fetch').then(({ default: fetch }) => fetch(...args));
const request = "https://accounts.spotify.com/api/token";
const client_id = "32-your-client-id-7b";
const client_secret = "ab-your-client_secret-9e";
const code = Buffer.from(client_id + ":" + client_secret).toString("base64");
const app = express();
const optionsTOKEN = {
method: "POST",
body: "grant_type=client_credentials",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic " + code
},
// json: true,
};
app.get("/code", async (req, res) => {
const data = await retrieveCode(request, optionsTOKEN);
console.log(res.statusCode)
res.send(data);
});
app.listen(8888, () => {
console.log("server running on port 8888");
});
async function retrieveCode(URlRequest, options) {
try {
const res = await fetch(URlRequest, options);
console.log(res);
const data = await res.json();
console.log("la data vaut" + JSON.stringify(data));
return data
} catch (err) {
console.log(`L'erreur: ${err}`);
}
}
#2 Using this dependencies
package.json for npm install
{
"dependencies": {
"express": "^4.18.2",
"node-fetch": "^3.3.0"
}
}
#3 npm install
#4 npm start
#5 access from browser http://localhost:8888/code
Response in console
la data vaut{"access_token":"BQCuVhXlpVQGKGxqK-remove-some-string-nX6sQp8uPSYBMh5lsU","token_type":"Bearer","expires_in":3600}
200
In Browser,

In node.js, the post method is connected to get and a 404 error appears

node.js, if you change the 'post' method to 'get' in the client, it works well, but 404 error appears only in the 'post' method. May I know why?
P.S Many people say the problem is caused by the failure to find the path '/api/insert/' on the server, but I don't think it's because it works well when you change to the 'get' method.
client code
const writePost = async () => {
axios.defaults.withCredentials = true;
const config = {
headers: {
withCredentials: true,
},
body: {
title: writeData.title,
content: writeData.content,
register: writeData.register,
},
};
try {
//Successful response
await axios
.post("http://localhost:8000/api/insert", config)
.then((res) => {
console.log(res);
console.log(res.config);
});
} catch (error) {
//Failed to respond
console.log("write error", error);
}
};
node code
const cors = require("cors");
const express = require("express");
const app = express();
const mysql = require("mysql");
const PORT = process.env.port || 8000;
const bodyParser = require("body-parser");
const db = mysql.createPool({
host: "",
user: "",
password: "",
database: "",
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors({ credentials: true, origin: true }));
app.post("/api/insert", (req, res) => {
var title = req.body.title;
var content = req.body.content;
var register = req.body.register;
const sqlQuery =
"INSERT INTO BOARD (BOARD_TITLE, BOARD_CONTENT, REGISTER_ID) VALUES (?,?,?);";
db.query(sqlQuery, [title, content, register], (err, result) => {
res.send(result);
});
});
I recreated your setup exactly (as described, adding writeData varible in client code, and app.listen(PORT) in server.js) and worked for me, the most possible cause is PORT is being defined to something else than 8000, it checks for process.env.port before hand, removing that fixes it.
Basically, if you enter the url path in your browser, it displays the 'get' method, so it is one-sided for the error to appear. To test the 'post' method, use the 'form' tag 'method' 'post', or the 'controller get post' or 'postman'.

POST data passed from frontend JS to Nodejs/Expressjs is always undefined

I have a frontend JS script that takes text input from an HTML text box and sends it to an expressjs server. The body of the POST request, though, is always undefined, or depending on how I tweak things, returning as "{ }" if I view it via console.log( ). As I'm new to this, I can't seem to see what's going wrong.
Front end js:
async function submitCity(){
let x = document.getElementById("wg_input").value;
console.log("Successfully captured city name:", x);
let toWeather = JSON.stringify(x);
console.log("Input data successfully converted to JSON string:", toWeather);
const options = {
method: 'POST',
mode: 'cors',
headers: {'Content-Type': 'text/plain'},
body: toWeather
}
fetch('http://localhost:3000', options)
.then(res => console.log(res))
.catch(error => console.log(error))
}
Backend:
// Dependencies
const express = require('express');
const bp = require("body-parser");
const request = require("request");
const jimp = require('jimp');
const cors = require('cors');
const wgServer = express();
const port = 3000;
// Dotenv package
require("dotenv").config();
// OpenWeatherMap API_KEY
const apiKey = `${process.env.API_KEY}`;
// Basic server initialization
wgServer.use(cors())
wgServer.use(bp.json())
wgServer.use(bp.urlencoded({ extended: true }))
wgServer.listen(port, function() {
console.log(`Example app listening on port ${port}!`)
});
wgServer.post('/', async function (req, res) {
res.set('Content-Type', 'text/plain');
console.log(req.body)
res.send('Hello World');
//const data = await req.body;
// let jsonData = JSON.stringify(req.body);
// res.status(201);
//res.json();
});
The returned data is supposed to be a string of about 15 characters, give or take a few (a city and state). I thank you in advance.

node express return request body empty by using API fetch POST

Learning nodejs and trying to post a form from HTML (with image upload) to nodejs (express) but the request.body returning empty object.
Tried few solutions on this site but no one is working.
Here is my code for creating a dynamic form. (HTML)
function show(data) {
const d = data.temp_form;
let content = ''
// console.log(d)
d.forEach((item) => {
if (item === 'image_backup' || item === 'image_banner') {
content += `<label for='${item}'>${item}</label><input name='${item}' type='file' id='${item}' value=''><br/>`
}else{
content += `<label for='${item}'>${item}</label><input name='${item}' type='text' id='${item}' value=''><br/>`
}
})
content += ` <input type="submit" id="handle_submit">`
getFormContianer.innerHTML = content
}
Code handling form submit
async function handleForm(e) {
e.preventDefault();
let dataForm = new FormData(e.target)
let obj = {}
dataForm.forEach((value, key) => {
obj[key] = value
if( typeof value === 'object'){
console.log(value.name)
obj[key] = value.name
}
});
let data = JSON.stringify(obj);
await fetch(file_api, {
method: 'POST',
body: data
}).then((res)=>{
return res.json();
}).then((data)=>{
console.log('api err: '+data);
}).catch((err) =>{
console.log('api err: '+ err)
})
}
Then, in my nodejs
const express = require('express');
const cors = require('cors');
const config = require('./config')
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
const app = express()
const templates = require('./routes/templates-routes');
const files = require('./routes/files-routes');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());
app.use(express.static('public'))
app.use('/api', templates.routes);
app.use('/create', files.routes);
app.listen(config.port, () => {
console.log(`Example app listening at http://localhost:${config.port}`)
})
and in the route.js
const express = require('express');
const router = express.Router();
const {replaceValue } = require('../controllers/filesController');
router.post('/file', replaceValue);
module.exports={
routes: router
}
for the fileController.js
const replaceValue = (request, response) =>{
console.log(request.body)
response.send(request.body)}
Hope that can get some comment for you, thank you so much!
let data = JSON.stringify(obj);
await fetch(file_api, {
method: 'POST',
body: data
You are passing a string to body and haven't specified a Content-Type header so fetch will generate a Content-Type: text/plain header.
Since plain text isn't JSON, the JSON parsing middleware you have set up in Express won't process it.
await fetch(file_api, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: data
Note that this will make it a preflighted request, so make sure you follow the instructions for the CORS module to support that.

Redirect image request on NodeJS

Inside my application code, for a specific set of APIs, I'm making a NodeJS request like following, which should return a image as the body. This same request works fine on Postman (and I can see the image).
module.exports = {
getThumbnail: function (thumbnailUrn, env, token, onsuccess){
request({
url: config.baseURL(env) + config.thumbail(thumbnailUrn),
method: "GET",
headers: {
'Authorization': 'Bearer ' + token,
}
}, function (error, response, body) {
// error check removed for simplicity...
onsuccess(body);
});
}
}
The above code run under my own security checks and adds the token header. It works fine (request calls return 200/OK).
Now on my app router I want to respond this as an image, but the output is not being interpreted as an image. Here is what I have:
var dm = require(/*the above code*/);
// express router
var express = require('express');
var router = express.Router();
router.get('/getThumbnail', function (req, res) {
var urn = req.query.urn;
dm.getThumbnail(urn, req.session.env, req.session.oauthcode, function (thumb) {
res.writeHead(200,
{
'Content-Type': 'image/png'
}
);
// at this point, the 'thumb' variable is filled
// but I believe is not properly encoded...
// or maybe the res.end output is missing something...
res.end(thumb, 'binary');
});
});
module.exports = router;
EDIT: as commented by Nodari Lipartiya, this is kind of proxy behaviour ( server(responds with image) -> proxy (node.js/resends to client) -> end user)
I'm not sure what is coming back in thumb, but the following snippet seemed to work for me (bypassing Express for simplicity):
var http = require("http")
var fs = require("fs")
var server = http.createServer(listener)
server.listen(() => {
console.log(server.address().port)
})
var binary = fs.readFileSync("path to local image")
function listener(req, resp) {
resp.writeHead(200,
{
'Content-Type': 'image/png'
}
);
resp.end(new Buffer(binary), "binary")
}
What happens if you wrap it in a Buffer?
If I've understood everything correctly:
I did this
server.js
var fs = require('fs');
var express = require('express');
var app = express();
app.get('/img', function(req, res, next) {
var stream = fs.createReadStream('img.jpeg');
var filename = "img.jpeg";
filename = encodeURIComponent(filename);
res.setHeader('Content-disposition', 'inline; filename="' + filename + '"');
res.setHeader('Content-type', 'image/jpeg');
stream.pipe(res);
});
app.listen(9999, function () {
console.log('Example app listening on port 9999!');
});
proxy.js
var request = require('request');
var express = require('express');
var app = express();
app.get('/img', function(req, res, next) {
console.log('proxy/img');
request({
url: 'http://localhost:9999/img',
method: "GET",
}, function (error, response, body) {
res.end(body, 'binary');
});
});
app.listen(9998, function () {
console.log('Example app listening on port 9998!');
});
req.js
var request = require('request');
request({
url: 'http://localhost:9998/img',
method: "GET",
}, function (error, response, body) {
console.log('body', body);
});
works for me. Please, let me know if you'll need help.

Categories