Angular consumes express web api , bad request - node.js

My angular app consumes a nodejs webapi :
var header = {
headers: new HttpHeaders()
.set('Authorization', `Bearer ${this.token}`)
}
var url="http://localhost:3000/user/deleteTodoFromUser/"+idUser+"/"+idTodo;
return this.http.put(url,"",header);
my api :
**router.put('/deleteTodoFromUser/:id/:idTodo', passport.authenticate('bearer'), (req, res) => {**
User.findByIdAndUpdate(req.params.id,{ $pull:{todos:{$in:[req.params.idTodo]}}},{new:true},(err, usr) => {
if (err) {
res.send(err);
}
if(usr)
{
res.send(usr);
}
else
{
res.status(400).send("bad request");
}
**My api works properly in postman **
** CORS are enabled **
in angular doesn't, it returns 400 (bad request )
let params = new HttpParams();
params = params.append('id', idUser);
params = params.append('idTodo', idTodo);
this.http.put(url, "", { headers: headers, params: params });
when I add params parameter in the request , It becomes like that
http://localhost:3000/user/deleteTodoFromUser/?id=5dfa958e98710030207952cc&idTodo=5dfa976ea4ea1d31f8919ee5
but the api waits the request like that :
http://localhost:3000/user/deleteTodoFromUser/5dfa958e98710030207952cc/5dfa976ea4ea1d31f8919ee5
the difference is my api waits the request id without id?= and idTodo?=
and I want it like that

400 Bad Request, Whatever the endpoint is expecting, it's not getting it.
Seems that there is an issue while passing params to your API or the token value sent to your API is invalid.
This is another way to send parameters to your API instead of Appending them to the URL
const headers = new HttpHeaders()
.set('Authorization', `Bearer ${this.token}`);
let params = new HttpParams();
params = params.append('id', idUser);
params = params.append('idTodo', idTodo);
this.http.put(url, "", { headers: headers, params: params });
If it's not the case try to make a call using real parameters value and a valid token that works in Postman in order to detect the root cause of the error that you are getting.

Related

Node Axios Create Global Token Variable for Use in Separate Variable Header

Using Node & Axios
What I Want to Do
In my server.js file, I want to call an api for a token that always changes, use axios (or other solution) to create a global token variable, and provide the global token to an app.get request header within an object, again, all within my server.js file.
What I'm Trying
I get the data using...
var data = '<tsRequest>\r\n\t<credentials name="name" password="pword">\r\n\t\t<site contentUrl="" />\r\n\t</credentials>\r\n</tsRequest>';
var config = {
method: 'post',
url: 'https://url.uni.edu/api/3.13/auth/signin',
headers: {
'Content-Type': 'text/plain'
},
data : data
};
I try to create the global token variable (this is where I'm struggling)...
const token= axios(config)
.then((response) => {
console.log(response.data.credentials.token);
}).catch((err) => {
console.log(err);
});
console.log(token)
I have a functioning app.get request where instead of manually providing the token, I want to use the const token...
app.get('/gql', async (req, res) => {
var someObject = {
'method': 'POST',
'url': 'https://diffurl.uni.edu/api/metadata/graphql',
'headers': {
'X-Some-Auth': token,
'Content-Type': 'application/json'
},
The Current Results
What I have for the var data = and the var config = and the axios(config) all work to return the token via console.log, but I have 2 issues using axios.
The Axios Issues
In my hopes of creating a global token variable, I only understand how to get a console.log result instead of returning a 'useful data object'.
In just about every piece of documentation or help found, the example uses console.log, which is not a practical example for learners to move beyond just returning the data in their console.
What do I need to provide in axios to create a global token object in addition to or instead of console.log?
I realize 1. is my current blocker, but if I run my app, I get the following:
Promise { <pending> }
Express server running on port 1234
abc123 [the console.logged token via axios]
I'm not sure what the Promise { <pending> } means, how do I fix that?
Beyond The Axios Issues
If the axios problem is fixed, am I passing the const token correctly into my app.get... var someObject... headers?
Thank you for any help you can provide.
This is what Axios interceptors are for.
You can create an Axios instance with an interceptor that waits for the token request to complete before adding the token to the outgoing request.
A response interceptor can be added to handle 401 statuses and trigger a token renewal.
const data = "<tsRequest>...</tsRequest>";
let renew = true;
let getTokenPromise;
const renewToken = () => {
if (renew) {
renew = false; // prevent multiple renewal requests
getTokenPromise = axios
.post("https://url.uni.edu/api/3.13/auth/signin", data, {
headers: {
"content-type": "text/plain", // are you sure it's not text/xml?
},
})
.then((res) => res.data.credentials.token);
}
return getTokenPromise;
};
const client = axios.create();
// Request interceptor to add token
client.interceptors.request.use(async (config) => ({
...config,
headers: {
"X-Some-Auth": await renewToken(),
...config.headers,
},
}));
// Response interceptor to handle expiry
client.interceptors.response.use(
(res) => res,
(error) => {
if (error.response?.status === 401) {
// Auth expired, renew and try again
renew = true;
return client(error.config);
}
return Promise.reject(error);
}
);
// if putting this in a module...
// export default client;
The first time you try to make a request, the token will be retrieved. After that, it will continue to use the last value until it expires.
if you want to create a to send the token with every request in axios you should create a custom axios instance or change the global axios default
you will find the way to do it here, about promise problem you need to resolve it using .then
this how i think you should do it
// first create axios instance
// you can set config defaults while creating by passing config object see the docs
const instance = axios.create();
// then get the token from API
axios(config).then(response=>{
instance.defaults.headers.common["header you want to set"]=response.data.credentials.token
});
// then use the instance to make any request you want that should have the token

forward the response of http request to the client

I am invoking a web service through an azure function in node.js with Axios, I have a couple of questions here.
1- in the body of this request I'm hardcoding the value for appUser. however, if I want to run this request on postman and pass the JSON value in the body for appUserwhat changes do I need to do in the code so the param value can pick up what is being passed.
2- the response for this request is only returned in the console of the editor but not getting sent to the client response body (i.e. postman) any idea how to forward the response?
module.exports = async function () {
const axios = require("axios");
const data = {
appUser: "yamen",
};
const headers = {
Authorization:
"Basic WUFNkVQRDg9",
};
{
axios
.post(
"https://tegossl/GetAppUser?company=Enva",
data,
{ headers: headers }
)
.then((response) => {
console.log(`Status: ${response.status}`);
console.log("data: ", response.data);
})
.catch((err) => {
console.error(err);
});
}
};

How to make a multipart request from node JS to spring boot?

I have a node js backend that needs to send a file to a spring boot application.
The file is local uploads/testsheet.xlsx.
Here is the code to upload the file using the form-data npm module and Axios.
const formData = new FormData()
formData.append("file", fs.createReadStream("uploads/testsheet.xlsx"));
formData.append("status", status);
const path = `/endpoint`
const auth = {
username: username,
password: password
}
const url = `${baseUrl}${path}`
const response = await sendRequest(url, auth, "POST", formData, null, null, null)
//sendRequest Code -
try {
const response = await axios({
method,
url,
data,
params,
headers,
auth,
config,
})
return response
} catch (err) {
console.log(`Fetch Error: => ${method}:${url} => ${err.message || err.response}`)
return err.response ? { error: err.response.data.message } : { error: err.message }
}
The Spring boot side has the following code -
#PostMapping("/endpoint")
public StatusResponse update(#RequestParam("file") MultipartFile file, #RequestParam("status") String status){
boolean response = transactionService.update(file, status);
return statusResponse;
}
On the spring boot side, I keep getting this error -
org.springframework.web.multipart.MultipartException: Current request is not a multipart request
While sending from the postman, everything works correctly.!!!
How do I send the multipart file successfully?
You should use the .getHeaders() function that the formData object provides, in order to correctly set the multipart form boundary, e.g:
const res = await axios.post(url, formData, {
headers: formData.getHeaders()
});

Getting LinkedIn access token through http request on node.js server

I am following the Authorization Code Flow (3-legged OAuth) documentation and I am now at step 3 where I need to use the authorization code in order to recieve an access token from LinkedIn. In the project I am using node.js, typescript and the node-fetch library. The following function creates a body with content type x-www--form-urlencoded since this is content type which LinkedIn require.
async function GetAccessToken(data: any) {
let body: string | Array<string> = new Array<string>();
for (let property in data) {
let encodedKey = encodeURIComponent(property);
let encodedValue = encodeURIComponent(data[property]);
body.push(encodedKey + "=" + encodedValue);
}
body = body.join("&");
const response = await fetch("https://www.linkedin.com/oauth/v2/accessToken", {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
body: body
}).then((res: any) => {
console.log("Result", res);
});
return response;
}
I do not recieve any errors and the response status is 200 but the response values I recieve are:
size: 0,
timeout: 0,
and what LinkedIn promise is:
access_token
expires_in
When I post the url with my parameters using postman the request goes through and I recieve the correct data which indicates the problem lies within my request function and not my values.
Any help is appreciated!
You need add all headers from postman
const urlencoded = new URLSearchParams();
urlencoded.append("client_id", env.LINKEDIN_CLIENT_ID);
urlencoded.append("client_secret",env.LINKEDIN_CLIENT_SECRET);
urlencoded.append("grant_type", "authorization_code");
urlencoded.append("code", code);
urlencoded.append(
"redirect_uri",
"http://localhost:3000/api/auth/linkedin-custom"
);
const accessTokenPromise = await fetch(
"https://www.linkedin.com/oauth/v2/accessToken",
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: urlencoded,
}
);

Podio API addItem call

I'm trying to implement https://developers.podio.com/doc/items/add-new-item-22362 Podio API addItem call in a nodejs module. Here is the code:
var _makeRequest = function(type, url, params, cb) {
var headers = {};
if(_isAuthenticated) {
headers.Authorization = 'OAuth2 ' + _access_token ;
}
console.log(url,params);
_request({method: type, url: url, json: true, form: params, headers: headers},function (error, response, body) {
if(!error && response.statusCode == 200) {
cb.call(this,body);
} else {
console.log('Error occured while launching a request to Podio: ' + error + '; body: ' + JSON.stringify (body));
}
});
}
exports.addItem = function(app_id, field_values, cb) {
_makeRequest('POST', _baseUrl + "/item/app/" + app_id + '/',{fields: {'title': 'fgdsfgdsf'}},function(response) {
cb.call(this,response);
});
It returns the following error:
{"error_propagate":false,"error_parameters":{},"error_detail":null,"error_description":"No matching operation could be found. No body was given.","error":"not_found"}
Only "title" attribute is required in the app - I checked that in Podio GUI. I also tried to remove trailing slash from the url where I post to, then a similar error occurs, but with the URL not found message in the error description.
I'm going to setup a proxy to catch a raw request, but maybe someone just sees the error in the code?
Any help is appreciated.
Nevermind on this, I found a solution. The thing is that addItem call was my first "real"-API method implementation with JSON parameters in the body. The former calls were authentication and getApp which is GET and doesn't have any parameters.
The problem is that Podio supports POST key-value pairs for authentication, but doesn't support this for all the calls, and I was trying to utilize single _makeRequest() method for all the calls, both auth and real-API ones.
Looks like I need to implement one for auth and one for all API calls.
Anyway, if someone needs a working proof of concept for addItem call on node, here it is (assuming you've got an auth token beforehand)
_request({method: 'POST', url: "https://api.podio.com/item/app/" + app_id + '/', headers: headers, body: JSON.stringify({fields: {'title': 'gdfgdsfgds'}})},function(error, response, body) {
console.log(body);
});
You should set content-type to application/json
send the body as stringfied json.
const getHeaders = async () => {
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json; charset=utf-8',
};
const token = "YOUR APP TOKEN HERE";
headers.Authorization = `Bearer ${token}`;
return headers;
}
const createItem = async (data) => {
const uri = `https://api.podio.com/item/app/${APP_ID}/`;
const payload = {
fields: {
[data.FIELD_ID]: [data.FIELD_VALUE],
},
};
const response = await fetch(uri, {
method: 'POST',
headers: await getHeaders(),
body: JSON.stringify(payload),
});
const newItem = await response.json();
return newItem;
}

Resources