How to send body data with headers with axios get request - reactjs

I am trying to get request from api that has a owner = value and date = value. Using Postman I can send a request with body json to get results. However when using Axios I can not get the results. How do I send body json to header and get results back. with Axios I am getting an empty response
does not work
var searchRecord = {
owner: 'wxTWH8zqSwaIXPAVsjZoRCkvjx73',
date: '2021-09-02',
};
var config = {
method: 'get',
url: 'http://localhost:3000/records/owner',
headers: {
'Content-Type': 'application/json',
},
body: searchRecord,
};
axios
.get('http://localhost:3000/records/owner', config)
.then(function (response) {
// handle success
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
})
in Postman I can send the following in the body and get the results I need
{
owner: 'wxTWH8zqSwaIXPAVsjZoRCkvjx73',
date: '2021-09-02',
}
output response will be:
{
"instantMessage": "false",
"isComplete": false,
"_id": "612e5cede496ce8f1b6a244c",
"date": "2021-08-31",
"title": "Ming first",
"description": "Test",
"remindTime": "1630432800",
"owner": "wxTWH8zqSwaIXPAVsjZoRCkvjx73",
}

I think I have the same problem.
When I'm using the postman to test my backend - everything work ok.
So the purpose is to get data from endpoint (and as body I want to provide user email):
data = {
"user_email": test#test.com
}
.get("api/test_endpoint/", config, data)
How to send body data and headers with axios get request?
Last comment in above topick "GET Body is allowed by the standards past 2014".
So finally is it possible or is it a correct practice?
Edit:
Of course I have to add:
It's possible to add needed data as part of get request url (but it's could not be login or pass!!!)
So for example logged in admin user has possibility to get data for some user via email like:
get('localhost/api/test_endpoint?user_email=test#test.com')
So why not use body as part of get request?

Related

Is there a way to send JSON data with the key not being in double quotes with Axios?

I'm trying to make an simple Login screen with my back-end already being done. The Login API is finished(after testing with POSTMan), however I've had issues with sending the JSON data back to my back-end in which it can read it.
const options = {
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
"Accept": "application/json" }
}
axios.post('http://127.0.0.1/register/',
{
email: data.get('email'),
password: data.get('password'),
//SchoolID: '123456789'
}, options)
While it does send the request data back to the server, unfortunately it sends it back in a way in which my back-end cannot read it.
"email" : "mytest#email.com" // How my front-end sends it
email : "mytest#email.com" // How I want it to be done(POSTMan does it this way)

Expressjs Server cannot handle Requests from the Outside

I have a ExpressJs Server with React Components. And the Server should handle Requests from Outside and one request should play a Song from the Spotify API when not currently playing.
app.post("/play", (req, res) => {
try {
// requesting to play uses query params
id = req.query.id;
currPlayingID = 0;
// get the currently playing song from the SPotify API
axios({
url: "https://api.spotify.com/v1/me/player/currently-playing",
method: "get",
headers: {
authorization: `Bearer ${access_token}`,
},
})
// set the currently Playing ID or to zero if nothing is playing
.then((response) => {
if (response.data !== null) {
currPlayingID = response.data.id;
} else {
currPlayingID = 0;
}
});
// only play the song if its not currently playing
if (id !== currPlayingID) {
// making a axios request to the Spotify API to play the Song with the ID
axios({
url: "https://api.spotify.com/v1/me/player/play/",
method: "put",
headers: {
authorization: `Bearer ${access_token}`,
},
data: {
uris: [`spotify:track:${id}`],
},
});
res.status(204);
}
} catch (error) {
res
.status(404)
.json({ message: "Couldn't get Info from Spotify API", error: error });
}
});
The Problem:
The Code works when I start the server on the device itself (so a local server on my Desktop PC), but when I start the Server on my RaspberryPI i cannot handle Requests to this endpoint /play. Yeah I updated all the IP Adresses, everywhere.
But the moer ointeresting part is using the React Client I get this error:
Failed to load resource: net::ERR_CONNECTION_REFUSED
Requesting with POSTMAN I get the following:
Mixed Content Error: The request has been blocked because it requested an insecure HTTP resource
And from a request using a python script I get on the server side:
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "AxiosError: Request failed with status code 400".] {
code: 'ERR_UNHANDLED_REJECTION'
}
I have no clue how to fix each error and if it is one fix. Basically I found out it is a Problem with rejeccting requests from outside localhost, because with cURL on my ssh terminal it works.
I'm learning express, so I m not an expert, but I'm looking at your errors. I will suggest you try asyncHandler module. It handles asynchronous requests and exceptions.
I faced a similar issue because while I'm sending the API request via
Axios, my token is null/empty/wrong, so make sure your token is correct
this is my request format
axios({
method:"POST",
url:"https://graph.facebook.com/v13.0/"+phon_no_id+"/message?access_token="+token,
data:{
messaging_product:"whatsapp",
to:from,
text:{
body:"Hi.. I'm Prasath"
}
},
headers:{
"Content-Type":"application/json"
}
});

How to send a POST request with variables in React?

I am learning how to send a POST request to an API with React.
What I'm trying to achieve right now is sending a POST request to an API.
The API will insert the event with something like this (what is this method called?):
https://api.com/WebService.asmx/insertEvent?event_id=5&desc=<p>HelloWorld</p>&name=testing
The method that I'm currently using as POST is shown at POST method and it returns me with the error unexpected token '<' in json at position 0 and the result that I get when I console.log(JSON.stringify(event)) is something like this:
{"event_id":"5","desc":"<p>HelloWorld</p>","name":"testing"}```
POST method
const response = await fetch('https://api.com/WebService.asmx/insertEvent',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(event)
})
Edit: I've fixed the above error by encoding the HTML that I need to send. This is now my latest POST method, but I'm still facing error 500 for some reason even though it works when I copy and pasted the URL+params from the console.log that has the error shown:
const addBulletin = async (event) => {
console.log(event, '--event')
const url = 'https://api.com/WebService.asmx/insertEvent';
axios.post(url, null, { params: {
title: event.title,
desc: event.desc,
image: event.image,
employee: event.employee,
entity: event.entity,
startDate: event.startDate,
endDate: event.endDate,
createdBy: event.createdBy
}})
.then(response => console.log(response.status))
.catch(err => console.warn(err));
};
Edit: I've tested the API on a vanilla JS project using .ajax with POST, and it works, so I think the API shouldn't be a problem.
var json = $('.insert-form').serialize();
$.ajax({
type: "POST",
url: "https://api.com/WebService.asmx/insertEvent",
data: json,
async: true,
success: function (response) {
alert("Event has been successfully created!");
},
error: function (response) {
console.log(response);
}
});
The API you are sending the request to expects a query parameter (data in the URL).
https://api.com/WebService.asmx/insertEvent?event_id=5&desc=<p>HelloWorld</p>&name=testing
In this request, we are sending 3 query params: event_id, desc, and name.
To send this kind of request from React, you should not use request body. Instead. I advise you to use axios to make it easier. It's a very powerful library, better than using fetch. It should be done this way:
axios.post(`https://api.com/WebService.asmx/insertEvent`, null, { params: {
event_id: eventId,
desc
}})
.then(response => response.status)
.catch(err => console.warn(err));
This may help: How to post query parameters with Axios?

Angular $http post call passing data issue to GO backend

I am trying to get access to backend written in GO which in 99% is good (problem does not lay there).
For now I just created simplest call which stay in controller (it will be in service in future) to register new user. Although I hardcoded data which I am passing the response says 403 forbidden. In powerShell shows reason of 403:
RegistrationForm parse - email: , nick:
Validation failed for email - blank
It looks like I am not passing my data correctly because email is blank. Please take a look at my code:
$ctrl.fake_registerSubmit = function() {
$http({
url: 'http://localhost:3000/v1/sign_up',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
data: {
email: 'check#onet.pl',
nick: 'borysxoxo',
password: 'admin12312',
password_confirmation: 'admin12312'
}
})
.then(function successCall(response, post) {
console.log('user added');
}, function errorCall(respone) {
console.log('error callback');
console.log(respone);
})
};
This screenshot presents API documentation which I am trying to access:
link
What am I doing wrong? Is there other way to pass data?
You are sending some json data with the wrong Content-Type.
I see 2 options, either change Content-Type in your header to:
'Content-type' : 'application/json'
or transform your payload to:
data: "email=check#onet.pl&nick=borysxoxo&password=admin12312&password_confirmation=admin12312"

Nodejs sending external API POST request

i am trying to send a POST request from my angularjs controller to the nodejs server which should then send a full POST request to the external API and this way avoid CORS request as well as make it more secure as i'm sending relatively private data in this POST request.
My angularjs controller function for making the post request to the nodejs server looks like this and it works fine:
var noteData = {
"id":accountNumber,
"notes":[
{
"lId":707414,
"oId":1369944,
"nId":4154191,
"price":23.84
}
]
}
var req = {
method: 'POST',
url: '/note',
data: noteData
}
$http(req).then(function(data){
console.log(data);
});
Now the problem lies in my nodejs server where i just can't seem to figure out how to properly send a POST request with custom headers and pass a JSON data variable..
i've trierd using the nodejs https function since the url i need to access is an https one and not http ,i've also tried the request function with no luck.
I know that the url and data i'm sending is correct since when i plug them into Postman it returns what i expect it to return.
Here are my different attempts on nodejs server:
The data from angularjs request is parsed and retrieved correctly using body-parser
Attempt Using Request:
app.post('/buyNote', function (req, res) {
var options = {
url: 'https://api.lendingclub.com/api/investor/v1/accounts/' + accountNumber + '/trades/buy/',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': apiKey
},
data = JSON.stringify(req.body);
};
request(options, function (error, response, body) {
if (!error) {
// Print out the response body
// console.log(body)
console.log(response.statusCode);
res.sendStatus(200);
} else {
console.log(error);
}
})
This returns status code 500 for some reason, it's sending the data wrongly and hence why the server error...
Using https
var options = {
url: 'https://api.lendingclub.com/api/investor/v1/accounts/' + accountNumber + '/trades/buy/',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': apiKey
}
};
var data = JSON.stringify(req.body);
var req = https.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
req.write(data);
req.end();
Https attempt return a 301 status for some reasons...
Using the same data, headers and the url in Postman returns a successful response 200 with the data i need...
I don't understand how i can make a simple http request...
Please note: this is my first project working with nodejs and angular, i would know how to implement something like this in php or java easily, but this is boggling me..
So after a lot of messing around and trying different things i have finally found the solution that performs well and does exactly what i need without over complicating things:
Using the module called request-promise is what did the trick. Here's the code that i used for it:
const request = require('request-promise');
const options = {
method: 'POST',
uri: 'https://requestedAPIsource.com/api',
body: req.body,
json: true,
headers: {
'Content-Type': 'application/json',
'Authorization': 'bwejjr33333333333'
}
}
request(options).then(function (response){
res.status(200).json(response);
})
.catch(function (err) {
console.log(err);
})

Resources