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
Related
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' })
}
})Ï
I am getting an error to GET data from my API endpoint.
I am able to send data and also update/ delete them from the postTodo()method.
I have added it in a useEffect()so that the I am able to send data to server whenever a Todo is completed or deleted.
But whenever i reload the page, in the devtools, the todos array is [].
Some help would be appreciated.Thanks.
The Todo.jsx
const postTodo = (todos) => {
console.log(todos);
axios.post("http://localhost:4000/api/todos", todos, {
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`,
}
})
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
})
}
useEffect(() => {
postTodo(todos)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [todos])
useEffect(() => {
axios.get("http://localhost:4000/api/todos", {
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`,
}
})
.then(res => {
console.log(res);
setTodos(res.data.todos)
})
.catch(err => {
console.log(err);
})
}, [])
the server.js
const authCheck = (req, res, next) => {
if (req.headers['authorization']) {
const token = req.headers['authorization'].split(" ")
if (token[0] !== 'Bearer') {
return res.send({ status: 'error', error: 'invalid request' });
} else {
req.jwt = jwt.verify(token[1], process.env.jwtSECRET);
return next();
}
}
}
app.post("/api/todos", authCheck, async (req, res) => {
const todos = req.body
console.log(todos);
const { id } = req.jwt
const user = await User.findByIdAndUpdate(id, { "todos": todos })
// console.log(user);
})
app.get("/api/todos", authCheck, async (req, res) => {
const { id } = req.jwt
const user = await User.findById(id)
log(user) //user.todos is empty
res.send({
status: "ok", todos: user.todos })
})
You can try something like this, where use effect for todos will log the value everytime you create a new todo
const postTodo = (todos) => {
console.log(todos);
axios.post("http://localhost:4000/api/todos", todos, {
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`,
}
})
.then(res => {
console.log(res);
getTodos()
})
.catch(err => {
console.log(err);
})
}
const getTodos = () => {
axios.get("http://localhost:4000/api/todos", {
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`,
}
})
.then(res => {
console.log(res);
setTodos(res.data.todos)
})
.catch(err => {
console.log(err);
})
}
const newTodo = () => {
const allTodos = [...todos];
allTodos.push("new Todo at:" + new Date())
postTodo(allTodos)
}
useEffect(() => {
console.log('todo-list', todos)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [todos])
useEffect(() => {
getTodos()
}, [])
return (<button onClick={() => }> Add Todo </button>)
The problem was solved,
actually it was the useEffect() issue.
I removed the UseEffect
and added the postTodos method after every useState hook updation.
I am trying to make a POST request to the GDMS api.
I keep getting the error code: 4000, which means "signature not exists"
I first obtain the token and return axios.create()
exports.client = async () =>{
return new Promise((resolve =>{
axios.get('https://www.gdms.cloud/oapi/oauth/token', {
params:{
username: username,
password: password,
grant_type: grant_type,
client_id: client_id,
client_secret: client_secret
}
}).then(res=>{
let client = axios.create({
baseURL: 'https://www.gdms.cloud/oapi/v1.1.0',
headers: {'authorization': `bearer${res.data.access_token}`}
})
return resolve(client)
}).catch(error=>{
console.log(error.message)
return resolve(false)
})
}))
}
That works fine.
Then I call the endpoint /sip/servers/list like so
await gdms.sipServers.list(client)
exports.list = async (client) =>{
return new Promise(resolve => {
let timestamp = new Date().toISOString()
client.post('/sip/server/list',{
timestamp: timestamp,
signature: sha256(`×tamp=${timestamp}&`)
}).then(res=>{
console.log(res.data)
return resolve(res.data)
}).catch(error=>{
console.log(error.message)
return resolve(false)
})
})
}
But I keep getting the same error "signature not exists"
Any help would be greatly appreciated.
This is the documents for the signature
https://doc.grandstream.dev/GDMS-API/EN/#api-157061470296601000002
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}`,
},
}
)
Axios Post request
// Create profile
export const createProfile = (profileData, avatar, history) => dispatch => {
dispatch(clearErrors());
const image = new FormData();
image.append("avatar", avatar, avatar.name);
axios
.post("/api/profile", image, profileData)
.then(res => history.push("/dashboard"))
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
Edit ---> Axios post request second attempt
// Create profile
export const createProfile = (profileData, avatar, history) => dispatch => {
dispatch(clearErrors());
const image = new FormData();
image.append("avatar", avatar, avatar.name);
image.append("user", profileData, profileData.username);
axios
.post("/api/profile", image)
.then(res => history.push("/dashboard"))
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
profileData is what i want in the req.body and avatar is what i receive in req.file in my back-end with multer, but what i receive is the req.file with the image but nothing in my req.body(Just an empty object)
This is my router in node
router.post(
"/",
upload.single("avatar"),
passport.authenticate("jwt", { session: false }),
(req, res) => {
console.log(req.body);
}
);
Try to implement in following way using FormData
handleSubmit(e)
{
e.preventDefault();
const err = this.validate();
if (!err) {
var formData = {
category: this.state.category,
course: this.state.course,
};
const { category, course } = this.state;
let fd = new FormData();
fd.append('Test', this.state.testFile, this.state.testFile.name);
fd.append('category', category);
fd.append('course', course);
console.log(fd);
axios({
method: 'post',
url: 'http://localhost:7777/api/uploadTest',
data: fd,
})
.then((response) => {
if (response.data == 'Success') {
alert('Test has been Added..!!');
}
else {
alert('Something went wrong');
this.setState({ category: '' });
}
// this.setState({success:'Alert: '+response.data});
})
.catch((e) => {
console.error(e);
this.setState({ success: 'Alert: Something went wrong' });
});
}
}
I consider your route as /api/profile in route file.
You don't show your header profileData.
It should be like this
const profileData = {
headers: { 'content-type': 'multipart/form-data' }
}
Then you can request to the server as you already did.