I have a node.js back-end server. Front-end is running on Angular 10.
I want to pass data from front-end to back-end using fetch
Front-end code :
testmariadb($event: MouseEvent) {
return fetch('/api/customQuery', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
sqlQuery: 'SELECT * FROM software'
})
})
}
Back-end code
app.post('/api/customQuery', async (req, res) => {
let test = req.body['sqlQuery']
console.log(test)
})
I get this error :
let test = req.body['sqlQuery']
^
TypeError: Cannot read properties of undefined (reading 'sqlQuery')
at /home/erwan/Documents/GitHub/serverAltertManager/index.js:90:22
What I'm doing wrong ?
Are using the middleware properly
const express = require('express');
const app = express();
app.use(express.json());
testmariadb() {
fetch('APIURL', {
method: 'POST',
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: JSON.stringify({
key: 'Value'
})
}).then((result)=>{
return result
})
}
Related
i have a angular project that calls a firebase function, my firebase function uses fetch to get a xml response, the problem is i dont know how to handle the xml response that needs to be sent back to my angular project..can anyone help please
firebase function
app.post('/provider', bodyParser.json(), async (req, res) => {
const response = await fetch(
'https://api.verify.example.com/identification/report_verification/',
{
method: 'POST',
body: req.body,
headers: {
'Content-Type': 'application/json' ,
'Authorization': 'Token 8c708fe3306f3f55644842a4d1f00561aa57b02e' }
})
const str = await response.text()
res.send(str)
})
I want to hide my API key when I am making a post request from my browser. I need to input a number plate and send the request to the API and the API responds me with details about it. I have managed to get this working with a GET request to another API by using nodeJS but I can't manage to make it work with a post request. Keep in mind the request needs information from my input field in the browser which is the registration number of the vehicle to send me information back about it.
Here is my function in my browser JS file.
const searchBtn = document.getElementById("search-btn")
function startFetch() {
let plate = document.getElementById("plate").value
let reg = {registrationNumber: `${plate}`}
fetch(`https://driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1/vehicles`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': `my key is here`,
},
body: JSON.stringify(reg),
})
.then(response => response.json())
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
};
searchBtn.addEventListener("click", startFetch);
Any help and method would be appreciated. Thanks in advance.
For anyone in the same boat. I have managed to achieve what I want.
Client side JS file:
function startFetch() {
let plate = document.getElementById("plate").value
let reg = {registrationNumber: plate}
fetch(`http://localhost:3000/v`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(reg),
})
.then(response => response.json())
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
};
And the backend using Express, NodeJS, body-parser and axios
require("dotenv").config()
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const axios = require('axios');
app.use(bodyParser.json());
app.use(express.static("src"))
//Env vars
const API_URL = process.env.API_URL
const API_KEY = process.env.API_KEY
app.post('/v', (req, res) => {
const body = req.body;
// Make a request to the backend API
axios.post(API_URL, body,
{
headers: {
"Content-Type": "application/json",
'x-api-key': API_KEY
}
}
)
.then((response) => {
// Return the response from the backend API to the client
res.send(response.data);
})
.catch((error) => {
// Handle any errors
res.status(500).send(error);
});
});
app.listen(3000, () => {
console.log('API proxy server is listening on port 3000');
});
You are already sending the body.
A very minor modification to you code:
function startFetch() {
let plate = "abc123";
let reg = { registrationNumber: `${plate}` };
fetch(`https://driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1/vehicles`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": `my key is here`,
},
body: JSON.stringify(reg),
}
);
}
startFetch();
You can see your api-key in the header (though you should never send secret via http):
Then in the body (in chrome they call it payload):
Background
I am passing variable from my frontend HTML file using axios
var idToken1 = result.getIdToken();
axios({
method: 'post',
url: '/trial',
data: idToken1,
headers: {'Content-Type': 'application/x-www-form-urlencoded' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
in my app.js under route getting this as output,here all the values are present in key and key values is empty. so i think i need a way to parse those keys first
{
'{"payload":{"cognito:username":"jatin","exp":1620965984,"iat":1620962384,"email":"xxxx#gmail.com"}}': ''
}
i want to extract "email":"xxxx#gmail.com"
update: in app.js i am already using express native parser app.use(express.json()); app.use(express.urlencoded({ extended: true }));`
A parser is required if you want to get the http body as object:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));
Then you can use req.body to get the http body sent by your html web:
app.post('/trial', function(req, res) {
var email = req.body.payload.email;
//etc
});
The problem was with axios. axios needed object to be send as json object.
var idToken1 = result.getIdToken();
the following code results in proper JSON object in my backend
axios({
method: 'post',
url: '/trial',
data: { idToken: idToken1 },
headers: { 'Content-Type': 'application/json' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
The Problem cause is 'Content-Type'
is should be 'application/json'
axios({
method: 'post',
url: '/trial',
data: idToken1,
headers: { 'Content-Type': 'application/json' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
I am new to NodeJS + Express development. I want to build a REST API that can receive JSON data via POST. I was able to build the API in Express and receive a json payload from a transmission from the postman software. But when I try to simulate the same behaviour with javascript's fetch() function from a web browser, my express rest api crashes with the following error:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at parse (/home/johncomputer/projects/tt/node_modules/body-parser/lib/types/json.js:89:19)
at /home/johncomputer/projects/tt/node_modules/body-parser/lib/read.js:121:18
at invokeCallback (/home/johncomputer/projects/tt/node_modules/raw-body/index.js:224:16)
at done (/home/johncomputer/projects/tt/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/home/johncomputer/projects/tt/node_modules/raw-body/index.js:273:7)
at IncomingMessage.emit (events.js:215:7)
at endReadableNT (_stream_readable.js:1184:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
I only have this one file called src/app.js in my express project:
const express = require('express')
const port = process.env.PORT
var cors = require('cors')
const app = express()
app.use(cors())
app.use(express.json())
router = express.Router()
router.post('/users', async (req, res) => {
try {
console.log("+++++++++++")
console.log(req)
console.log("=========")
res.status(201).send({ "world":true })
} catch (error) {
res.status(400).send(error)
}
})
app.use(router)
app.listen(port, () => {
console.log(`Server running on port ${port}`)
})
I'm not sure if I'm using cors() correctly, but I threw it in there to get around a pre-flight OPTIONS issue that was causing my fetch() to generate a failed network connection error (which didn't occur for postman).
This was my javascript fetch code:
const postData = {"name":"John","email":"john#john.com","password":"chocolate-raisins!!!"};
fetch("http://johnserver.com:3000/users", {
method: "POST",
headers: {'Content-Type': 'application/json'},
body: postData
}).then((response)=>{
console.log(response);
if(!response.ok) return {}
return response.json();
}).then((result)=>{
console.log(result);return;
}).catch(function(error){
alert("Post Request Error: "+error.toString());
});
What am I doing wrong that's causing my API to fail with fetch() but not with postman?
EDIT
The output of the response variable from my fetch is this:
Response { type: "cors", url: "http://johnserver.com:3000/users", redirected: false, status: 400, ok: false, statusText: "Bad Request", headers: Headers, body: ReadableStream, bodyUsed: false }
The output of the result variable from my fetch is this:
{ }
On your fetch method please do this.
Insead of body:post Data do --> JSON.stringify(postData)
And also on your then function first return response.json() and then
check whatever parameters you want.
You're not sending valid you need to stringify your object.
fetch("http://localhost:3000/users", {
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ "name": "John", "email": "john#john.com", "password": "chocolate-raisins!!!" })
}).then((response) => {
if (!response.ok) {
return {};
}
return response.json();
}).then((response) => {
console.log(response); return;
}).catch(function (error) {
alert("Post Request Error: " + error.toString());
});
I'm posting the data {id: "abc123", text: "sometext"} to a node API. Posting from a component with action call:
export function addTextToAPI(inputData) {
return(dispatch) => {
console.log(inputData),
dispatch(addText(inputData))
fetch(myapi, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'POST',
data: inputData
})
.then(res => res.json())
}
}
console.log(inputData) is {id: "abc123", text: "sometext"}
node:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/addtest', (req, res) => {
console.log(req.body); // <= returns blank object {}
console.log(req.body.data); // <= returns undefined
console.log(req.query); // <= returns blank object {}
console.log("test added");
});
app.listen(3000);
I want to be able to read the inputData in req. How do I do that? I want to be able to read the inputData in req. How do I do that?
To post data you need to pass in a body param to fetch.
This should work:
export function addTextToAPI(inputData) {
return(dispatch) => {
console.log(inputData),
dispatch(addText(inputData))
fetch(myapi, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify(inputData)
})
.then(res => res.json())
}
}