How to send data to REST api in angular - javascript

I am trying to send basic auth header to Paypal api but can not get the format right. I read somewhere that I have to Base64 encode the credentials but that does'nt worked well and no response is generated. Here is the request I would like to send to REST API
var options = {
url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
method: 'POST',
headers: 'application/json',
auth: {
'user': 'XXXXXX',
'pass': 'YYYYYY'
}}
Sample request in curl which I wish to send in javascript
Paypal get access token api
under the heading POSTMAN
What will be correct structure to send this request?

I was missing the : thing now I can get the correct Base64 value and concatenate to authorization header and its working fine

Related

add query string to all requests ( post , get )

I want to add query string to all requests (post and etc) with Jquery or pure Javascript.
for example : domain.com?debug=true
I want to when click a button and its Ajax , this query string add.
Thank you in advance for your guidance.
I concluded that this is not a good question
you can use the body property which lets you send data to the server
for example:
fetch("URLHERE", {
method: "POST",
body: JSON.stringify({debug: true}),
headers: { // this lets you send data in json format
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
})
.then(res => ...)
please note: you need to send the data in string format, thats why i used JSON.stringify
check here for refernce : https://javascript.info/fetch-api
EDIT: DO NOT use body in GET request
check here why: HTTP GET with request body
if you want to send data to the server you usually use POST
if you want to get data from the server with get you need to send http request with the url you want and you can also send in with query
for ex:
my endpoint is "https://api.getCoolData.com/?debugger=true
and in your server you can take the query part the use it

GET request working through Postman but the browser tells me GET request cannot have body

I'm simply trying to send some urlencoded parameters via a GET request using fetch. I'm just trying to print the parameters using Express at the moment, like so:
app.get('/api', function (req, res) {
console.log(req.body);
res.sendStatus(200);
return;
});
This works just fine in Postman using a GET request and x-www-form-urlencoded key-value pairs. The webserver will print all the key-value pairs just fine.
But when I try and use fetch to do the exact same thing I get nothing but problems. I've tried two different methods:
fetch(`http://localhost:3000/api?user=test&password=123`, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
The request does go through using this method, but the webserver only prints {} - an empty object.
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("user", "test");
urlencoded.append("password", "123");
var requestOptions = {
method: 'GET',
headers: myHeaders,
body: urlencoded,
};
fetch("localhost:3000/api", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
The request does not go through using this method, and the browser gives me the error TypeError: Window.fetch: HEAD or GET Request cannot have a body.
This code was generated using the request that works in Postman using the generate code snippets option.
What am I doing wrong?
The parameters in this URL:
http://localhost:3000/api?user=test&password=123
are in the query string, not in the body and thus the content-type does not apply to them - they are properly encoded to be in a URL. In Express, you would access these with req.query. You should see a value for req.query.user and req.query.password in your Exprss request handler.
Note, it is not recommended that you send user credentials in a URL like this because URLs are often present in log files at your ISP, at the recipient server, in proxies, in your browser history, etc... User credentials like this should be sent in POST request over https where the credentials would go encoded in the body (where it won't be logged or saved by intermediaries).
The fetch error is accurate. GET requests do not have a body sent with them. That would be for POST or PUT requests. A GET request is a "get" request for a resource that you specify only with a URL.
You're confusing request body with a query string.
Your second request (you don't need a Content-Type for it)
fetch("http://localhost:3000/api?user=test&password=123");
would be handled by the following Express function:
app.get('/api', function (req, res) {
console.log(req.query); // Note that query, not body is used.
res.sendStatus(200);
return;
});
You can access fields from the query object as req.query.user && req.query.password.
As for having a request body in a GET request: while RFC doesn't explicitly fordbid it, it requires server to not change response based on the contents of the body, i.e. the body in GET has no meaning in the standard, so JS HTTP APIs (both fetch & XmlHttpRequest) deny it.
firstly if you are trying to get some data from your API or others API you should do GET request in order to get your desired data from server for example, if you want to get a specific things like a user or something else you can pass your data in GET request URL using query string or route params.
secondly, if you want to authenticate and send your credentials to the server its not recommended to use GET request as i said earlier GET request simply is for fetching some data from server, so if you want to send your credential or anything else you are better off using POST request to send data to the server and you can't do POST request in the browser, so you have to use something like postman or insomnia in order to send your POST request to the server. i hope it could help you to solve your issue.

how i can implement a get method to a api what needs "Temporary Headers"?

I made an api using Net.Core 'https://localhost:44351/api/usuarios' with Authorize attribute for use a validation token for access to this api. This token is generated by another api and works well.
When i use Postman for acess to api 'https://localhost:44351/api/usuarios' i need put in the Authorization tab the token previously generated (see https://i.ibb.co/Lg7rD4N/2.png) and this way i get access for the api (see https://i.ibb.co/0BqnPhR/3.png)
But the huge problem is when i try from a JAVASCRIPT CLIENT use method GET using FETCH. I know need to do a object like this for make correct request
let params= { method: 'GET',
headers: {"X-Auth-Token": "5f5fe128570248a9bd198add1a5b25e4"}
};
So my question is how i can implement the attributte 'Temporary-Headers' in the object 'params' like Postman does ( https://i.ibb.co/0BqnPhR/3.png)?
"Temporary Headers" are just like any other Header, those are just values auto-generated by the web client. I believe your problem relies on how you send your Header if you are using the fetch API modify your parameters like the following.
{
method: 'GET',
headers: {
"Authorization": "Bearer <replace with your token>"
}
}
This is how postman is sending the request as seen in the screenshots you provide.

sending cookies with ajax request via fetch api

In a nodeJs app, i am sending multipart/form-data to the server via ajax request. I am also using csurf package to guard against csrf attacks
Problem
When i submit my form without ajax request, everything works fine but when i submit my form using ajax request, i get invalid csrf token error on the server.
As far as i have understood the cause of this error, its because of cookies not sent with the request.
To send the cookies with ajax request, i set credentials: 'same-origin' in the post request made via fetch api but that didn't fix the issue. I also tried setting credentials: 'include' but that didn't make any difference.
Question
Is my understanding correct that this issue is because of cookies not being sent with ajax request and how can i fix this issue?
Code
let response = await fetch(requestUrl, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'multiplart/form-data'
},
body: new URLSearchParams(form)
});
When using fetch()/AJAX with csurf, you need to pass the CSRF token as a request header:
// Read the CSRF token from a hidden input in the form
const token = document.querySelector('input[name="csrf-token"]').value;
// POST using the Fetch API
fetch('/<route.name>', {
headers: {
// pass the csrf token as a header
'CSRF-Token': token
},
method: 'POST',
body: {
...
}
});

cURL command works, but Fetch API call returns 200 with 400 validation error in Response Payload

Having a huge issue I came across in sending a POST request using Fetch to get a URL shortened.
I am good and able to do a POST request by cURL command to this url shortener API:
Curl command
curl -d 'api_key=xxxxxxxxxxxxxx&url=https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch' http://fakeurlforexample/api/shorten/
Response
{"url": "https://fakeurlforexample/BdzfM3", "long_url": "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch", "name": "BdzfM3"}
And I get this great response payload from the API.
But when I do this by Fetch with this code I provided below, I get a 200 OK and in the response payload I have a 400 validation error that I am missing the API key.
However, the request payload in the developer console shows that the parameters were passed on properly to the API (I think...)
{"api_key":"xxxxxxxxxxxxxxxxx","url":"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch"}
Here is my code:
let get_url = 'http://fakeurlforexample.com/api/shorten/';
let request = new Request(get_url, {
method: 'POST',
body: JSON.stringify({'api_key':'xxxxxxxxx', 'url': 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch'})
});
fetch(request)
.then(function() {
console.log(request);
console.log(request.url);
})
Does anyone see the mistake I am making here?
Been beaten down by this for across hours upon hours this week now. Thanks for any help and assistance! And no, I can't easily transition the code to axios as it is right now. This is a demonstration so I'm really just trying to get it to work.
From the curl manpage Options section on -d, --data <data>:
(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Compare to -F, --form.
Whereas with your request, you are sending a JSON object (Content Type: application/json):
let request = new Request(get_url, {
method: 'POST',
body: JSON.stringify({'api_key':'xxxxxxxxx', 'url': 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch'})
});
Since you know the API endpoint accepts application/x-www-form-urlencoded because the curl request succeeds, you can set the content type as application/x-www-form-urlencoded and send the body as a string:
let request = new Request(get_url, {
method: 'POST',
headers: new Headers({'content-type': 'application/x-www-form-urlencoded'}),
body: 'api_key=xxxxxxxxxxxxxx&url=https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch'
});
Maybe its because you are defining headers 2 times.

Categories

Resources