I am trying to display this to front-end(html) part but i am not able to see it in browser console.I have tried without the "app.get" part. It does work when i run nodejs but it doesnt display it in browser. url and api-key is removed from here for safety reasons.
const express = require('express');
const app = express();
const fetch = require('node-fetch');
let url ='url';
let apiKey = 'api-key';
app.get('/', req, res =>{
res.sendFile(path.join(__dirname,'index.html'));
fetch(url,{
method: 'GET',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Basic ' + apiKey,
'Access-Control-Allow-Origin':'*'
},
credentials: 'same-origin'
})
.then(res =>res.json())
.then(data => console.log(data))
.catch(err => {
console.log(err);
})
})
app.listen(3000, () => {
console.log('Example app listening on port 3000!')
});
I fixed it. the path was messed up because i didn't have "const path = require('path');" and i fixed it. But also req wasn't defined so i had to put it inside a function app.get('/', function(req, res). Thank you for the help
Related
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.
I'm using ionic angular in frontend and I' trying to send a formdata that contains a file and also 2 strings. Apparently its being sent however I don't know how to read that information on the server side
FRONTEND
private fil3: File;
changePicture(fileChangeEvent){//this functions is called by an input file
this.fil3 = fileChangeEvent.target.files[0];
let a1 = "a1"
let a2 = "a2"
let b1 = "b1"
let b2 = "b2"
let formData = new FormData();
formData.append('photo', this.fil3, this.fil3.name);
formData.append(a1, a2);
formData.append(b1, b2);
fetch('http://localhost:3000/up', {
method: 'POST',
body: formData,
headers:{
/* 'Content-Type': 'application/json' */
'Content-Type': "multipart/form-data"
},
mode: "cors",
}).then(res =>{ res.json().then((data)=>{
console.log("filename: "+data.filename);
console.log("originalname: "+data.originalname);
console.log("message: "+data.message);
this.avatar="../../assets/uploads/"+data.filename
})
})
.catch(error => {console.error('Error:', error)})
.then(response => {console.log(response)});
}//changePicture
SERVER
function updatePicture (req, res) {
console.log("req.body: "+req.body)
}
On the server side I'm just trying to read each element of the formdata individually so I can work with them. These elements are the file and two other strings(a1,a2,b1,b2). This console.log on the server prints this req.body: [object Object]
I tried things like
console.log("req.body: "+req.body.a1)
console.log("req.body: "+req.body.[1])
but certainly do not work, I get undefined, I have no idea how to handle this, any word of advice?
MINIMUN REPRODUCIBLE CODE OF BACKEND
const express = require ('express')
const bodyParser = require ('body-parser')
const app = express()
const api = express.Router()
const cors = require('cors')
app.use(bodyParser.urlencoded({ extended:false}))
app.use(bodyParser.json())
app.use(cors({
origin: true
}));
const PORT = 3000;
app.listen(config.port, ()=>{
console.log(`Server running on port: ${PORT}`)
})
api.post('/up', (req, res) =>{
console.log(req.body)
})
Firstly, remove this part :
headers:{
/* 'Content-Type': 'application/json' */
'Content-Type': "multipart/form-data"
}
because if you define Content-Type manually, you can't inform about boundary information. It need to managed automatically by browser because you send files too.
Secondly, you need a library to parse you're multi-part data. You can use formidable :
const formidable = require('formidable');
//You're other codes
app.post('/up', (req, res) => {
const form = formidable({ multiples: true });
form.parse(req, (err, fields, files) => {
console.log('fields: ', fields);
console.log('files: ', files);
res.send({ success: true });
});
});
For my side this log something like :
fields: { a1: 'a2', b1: 'b2' }
files: {
file: PersistentFile {
...
I'm making an http post request to my express web server sending dummy data as json. It correctly receives the request and can send back a json object, but for some reason it can't manage to access the post request body.
I'm using this code for express:
const express = require('express');
const app = express();
const port = 3000;
app.post('/test', (req, res) => {
console.log(req.body);
res.json({"some": "thing"});
});
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}`)
});
And this is the code of the request:
const req = http.request({
hostname: '127.0.0.1',
port: 3000,
path: '/test',
method: 'POST',
json: {
url: "https://www.nothing.com",
name: "hello"
}
}, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', d => {
process.stdout.write(d)
})
})
req.on('error', error => {
console.error(error)
})
req.end()
As you can see I'm running this locally. The client receives a status code 200 and the json {"some": "thing"} sent by the server, but the server gets "undefined" from req.body. I tried using:
headers: {
'Content-Type': 'application/json'
}
body: JSON.stringify({
url: "https://www.nothing.com",
name: "hello"
})
instead of json directly in the request options, but to no avail. I even tried using app.use(express.json()); as someone suggested.
What is the problem?
Apparently the way I was doing the post request was not correct, I had to send the body in a separate line with req.write(), like this:
const http = require('http');
const data = JSON.stringify({ //<--- data to send as body
url: "https://www.nothing.com",
name: "hello"
});
const req = http.request({
hostname: '127.0.0.1',
port: 3000,
path: '/test',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}, res => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', d => {
process.stdout.write(d);
})
})
req.on('error', error => {
console.error(error);
})
req.write(data); //<--- this line
req.end();
You have to add body-parser middleware http://expressjs.com/en/resources/middleware/body-parser.html
req.body empty on posts
I want to be able to send data from one server to another, started on the same device (to start with). I have this:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const urlEncodedParser = bodyParser.urlencoded({extended: false});
app.post('/test', urlEncodedParser, (request, response) =>
{
console.log(request.body);
});
app.listen(9999);
console.log('Server started on port 9999');
const unirest = require('unirest');
unirest.post('http://127.0.0.1:9999/test').headers({'Accept': 'application/json', 'Content-Type': 'application/json'}).send({"test1": 123321, "test2": "321123"})
.then((response) =>
{
console.log(response.body);
});
It looks logical, but console.log(request.body); gives empty object {} yet in the post requests I do send some data using .send. How to get access to that data in the request?
You are sending data with Content-Type: 'application/json', so on the server you need to connect middleware not for urlencoded, but for json. In addition, you do not need to separately connect the body-parser since it is included in express and you can connect the necessary middleware like this:
Server:
const express = require('express');
const app = express();
app.post('/test', express.json(), (request, response) => {
console.log(request.body);
response.end('OK');
});
app.listen(9999, () => console.log('Server started on port 9999'));
Client:
const unirest = require('unirest');
unirest
.post('http://127.0.0.1:9999/test')
.headers({ Accept: 'application/json', 'Content-Type': 'application/json' })
.send({ test1: 123321, test2: '321123' })
.then((response) => {
console.log(response.body);
});
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'))