Cannot add data into elastic using axios from nodejs - node.js

I am trying to import data into elastic search using axios and nodejs but I am getting 400 bad request error, I have created index in elastic which is sales-enable-data index I am trying to add data using that index but I am getting bad request error
Code
app.get("/import/data", async (req, res) => {
const current = {
project_name: "java",
delivery_manager: "Yawhe",
project_manager: "Ruth",
};
const data = JSON.stringify(current);
await axios({
url: "http://localhost:9200/sales-enable-data-index/_doc",
method: "POST",
headers: {
"Content-Type": "application/json",
},
auth: {
username: "username",
password: "password",
},
body: data,
})
.then((response) => {
return res.status(200).send(response);
})
.catch((err) => {
return res.status(500).send(err);
});
});
Error
"code": "ERR_BAD_REQUEST",
"status": 400

Check the Axios request. Request unable to find the endpoint

You're sending String instead of JSON, this is why ElasticSearch says it does not like the data it's receiving.
Try doing the request without the JSON.stringify like this:
app.get("/import/data", async (req, res) => {
const current = {
project_name: "java",
delivery_manager: "Yawhe",
project_manager: "Ruth",
};
await axios({
url: "http://localhost:9200/sales-enable-data-index/_doc",
method: "POST",
headers: {
"Content-Type": "application/json",
},
auth: {
username: "username",
password: "password",
},
body: current,
})
.then((response) => {
return res.status(200).send(response);
})
.catch((err) => {
return res.status(500).send(err);
});
});

Related

Auth0 sync userinfo

I'm trying to sync my auth0 userinfo with my local database:
userRouter.get("/sync", validateAccessToken, (req, res) => {
var request = require("request");
var usertoken;
var options = { method: 'POST',
url: 'https://MYDOMAN.eu.auth0.com/oauth/token',
headers: { 'content-type': 'application/json' },
body: '{"client_id":"myclienttoken","client_secret":"myclientsecret","audience":"https://MYDOMAIN.eu.auth0.com/api/v2/","grant_type":"client_credentials"}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
usertoken = body;
console.log(body);
});
var auth0options = {
method: "GET",
url: "https://MYDOMAIN.eu.auth0.com/api/v2/users",
params: {id: 'email:"testuser"', search_engine: 'v3'},
headers: {
"content-type": "application/json",
authorization: `Bearer` + usertoken.access_token,
},
};
axios.request(auth0options).then(function (response) {
console.log("RES DATA: ", response.data);
})
.catch(function (error) {
console.error(error);
});
console.log("called");
res.status(200).json("message");
});
The following line, results in a error:
authorization: Bearer + usertoken.access_token,
"Cannot read properties of Undefined (reading 'access_token)"
But I don't get the userinfo when calling the auth0 api with that token.
I'm using the audience from the Auth0 Management API ex:
https://MYDOMAIN.eu.auth0.com/api/v2/
And not the audience from my own API, as I have read that's the correct way:
https://mydomain
Any ideas on what I'm doing wrong?

Why is req.body empty {} (GET REQUEST)

This is my Frontend code
const fetchData = () => {
const options = {
method: 'GET',
url: 'http://localhost:1337/user/chart',
headers: {'x-access-token': sessionStorage.getItem('token')},
body: [chartData.datasets]
}
axios.request(options).then((response) => {
console.log(response)
}).catch((error) => {
console.error(error)})
}
This is backend
app.get('/user/chart', async (req, res) => {
const token = req.headers['x-access-token']
if (!token){
return res.status(404).json({ success: false, msg: "Token not found" });
}
try {
const decoded = jwt.verify(token, process.env.access_secret)
const email = decoded.email
await User.updateOne(
{ email: email },
{ $set: {} },
)
console.log(req.body)
return res.status(200).json({message: 'ok', label:[]})
} catch (error) {
console.log(error)
res.json({ status: 'error', error: 'invalid token' })
}
})
When I console.log(req.body) it is an empty {}.
Why is it empty?
I am using a GET request to retrieve the chart data
Axios API does not accept body on get get request you can send parameters with params example
const url = '/user/chart';
const config = {
headers: {'x-access-token': sessionStorage.getItem('token')},
params:{someKey:chartData.datasets}
};
axios.get(url, config)
Axios doesn't support setting a body for a get request, see the docs or this related question.
Though, I'd also recommend to reconsider your design. Typically the body isn't used in a GET request. If you're sending data to the server, you likely want to use POST or PUT instead. If you just want to pass a parameter, then you likely want to use request parameters.
If you absolutely need to send a body in your GET request, then you'll need to use a different tool.
frondend //
const fetchData = () => {
const options = {
method: 'POST',
url: 'http://localhost:1337/user/chart',
headers: {'x-access-token': sessionStorage.getItem('token')},
body: {name : "xx",mail:"xx#"}
}
axios.request(options).then((response) => {
console.log(response)
}).catch((error) => {
console.error(error)})
}
backend //
app.post('/user/chart', async (req, res) => {
const {name , mail} = req.body
const token = req.headers['x-access-token']
if (!token){
return res.status(404).json({ success: false, msg: "Token not found" });
}
try {
const decoded = jwt.verify(token, process.env.access_secret)
const email = decoded.email
await User.updateOne(
{ email: email },
{ $set: {} },
)
console.log(req.body)
return res.status(200).json({message: 'ok', label:[]})
} catch (error) {
console.log(error)
res.json({ status: 'error', error: 'invalid token' })
}
})Ï

React.js Passport Authentication unable to get req.user from client

I am trying to authenticate a user through some API configured with passportjs. When I run the authentication request I get the redirect to the success route, but I can't get req.user. I tried through Postman and it works. I don't know what I'm forgetting. Could anyone help me?
This is my success route:
app.get("/success", async (req, res) => {
if (req.user){
return res.status(200).json({
user: req.user,
message: "Logged"
});
}
else {
return res.status(401).json({
message: "User authentication failed"
});
}
});
This is my react code:
const handleSubmit = (e) => {
e.preventDefault();
fetch("http://127.0.0.1:3001/login", {
method:"POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
redirect: "follow",
body: JSON.stringify({email: email, password: password})
}).then(resp => {
return resp.json();
}).then(data => console.log(data))
}
While you are calling the success/ route you need to add the authorization header along with the fetch request. We need to add the Basic jwt | authentication token as the authorization key
const response = await fetch(apiURL, {
method: 'GET',
headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${token}`,
// add the basic jwt | drf token for Authorization Key
},
body: JSON.stringify(yourNewData)
})

Why do I get Error 401 trying to patch Auth0 app_metadata with the Management API?

I'm banging my head against the wall trying to solve issuing a patch request after getting an access token. This same access token works for get requests to https://${appDomain}/api/v2/users/${userid}. But it fails with "Request failed with status code 401" when trying to use it to patch app_metadata.
Using NodeJS and Axios.
axios
.post(`https://${appDomain}/oauth/token`, {
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret,
audience: `https://${appDomain}/api/v2/`,
})
.then(({ data: { access_token, token_type } }) => {
const jwt = jwtDecode(access_token)
axios
.patch(`https://${appDomain}/api/v2/users/${userid}`, {
data: {
app_metadata: { stripeCustomerId: customer.id },
},
headers: {
Authorization: `${token_type} ${access_token}`,
},
})
.then(({ data }) => {
console.warn('patch response', data)
})
.catch((err) => {
console.error('patch error', err) // <--- ERROR 401 happens here
res.send(err)
})
})
.catch((err) => {
console.error('token error', err)
res.send(err)
})
After shadow boxing documentation I discovered a syntax error in my axios.patch call. Format should have been the following, which fixed my problems. I was passing data:{...} when it should have been like this:
axios.patch(
`https://${appDomain}/api/v2/users/${userid}`,
{
app_metadata: { stripeCustomerId: customer.id },
},
{
headers: {
Authorization: `${token_type} ${access_token}`,
},
}
)

How to fetch a specific field from axios post API request

I am using the below piece of code
const axios = require('axios')
axios
.post('https://xxx', {
"audience": "http://xxxx",
"grant_type": "xxxxx",
"client_id": "xxxxx",
"client_secret": "xxxxx"
})
.then(res => {
console.log(res)
})
.catch(error => {
console.error(error)
})
And I wanted assign the "res.data.token" to a variable token and use the variable in below code
describe('/GET device information', function () {
it("it should GET a Good Auth Status", function(done) {
chai.request('http:xxxxxx')
.get('xxxxxxxxxxxx')
.set({ "Authorization": `Bearer ${token}` })
.then((res) => {
(res).should.have.status(200);
// console.log(body) - not really needed, but I include them as a comment
done();
}).catch((err) => done(err))
});
})
you could wrap it in a try/catch and destructure the object:
try {
const res = await axios.post('https://xxx', {
'audience': 'http://xxxx',
'grant_type': 'xxxxx',
'client_id': 'xxxxx',
'client_secret': 'xxxxx'
})
const { data, token, foo, bar, status } = res.data
(status).should.equal(200)
} catch(e) {
console.log(e)
}
}
quick example

Resources