whats up!
i am trying to send a request with json parameters and i don't understand why in the server side
the parameter doesn't being send
let res = fetch("http://localhost:1000/vacations/" + vacation.id, {
method: "DELETE",
headers: { "Authorization": localStorage.token },
body: { "picture": vacation.picture }
})
i am trying to view the picture in the parameter in the server side
i use in node.js server the middleware express.json
and still i cant get this parameter :(
You may send a stringify body using JSON.stringify.
const res = fetch(`http://localhost:1000/vacations/${vacation.id}`, {
method: "DELETE",
headers: {
Authorization: localStorage.token
},
body: JSON.stringify({
picture: vacation.picture
})
})
Related
I have a function which uses Axios to send a POST request which goes through successfully and I get the right response. Now I want to try using fetch to do the exact same POST request. Unfortunately, the fetch request returns a 415 Unsupported Media Type response error and I have no idea why.
Currently:
onBeforeUnload = () => {
try {
const defaultPresence = {
presence: 'AVAILABLE',
message: '',
};
const url = getServerURL() + urls.PRESENCE;
axios.post(
url,
defaultPresence,
{
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
},
);
} catch (error) {
console.log(error);
}
}
The fetch code I've used to replace the Axios POST request.
fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
body: defaultPresence,
});
fetch does not recognise plain objects as the body.
If you want to send JSON then you need to encode the data and set the content-type header yourself.
fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${getAccessToken()}`,
"Content-Type": "application/json",
},
body: JSON.stringify(defaultPresence),
});
I am trying to make a call using JavaScript's Fetch API to generate an OAuth Token but I keep receiving a 400 response code and I'm not sure why. I wrote the key and secret to the console to verify their values, and I made the same API call using cURL (with the response I expected). Is there a small issue in my syntax?
fetch('https://api.petfinder.com/v2/oauth2/token', {
method: 'POST',
body: 'grant_type=client_credentials&client_id=' + key + '&client_secret=' + secret
}).then(r => { response = r.json() });
If the request body is a string, the Content-Type header is set to text/plain;charset=UTF-8 by default. Since you're sending urlencoded data, you have to set the Content-Type header to application/x-www-form-urlencoded.
fetch('https://api.petfinder.com/v2/oauth2/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'grant_type=client_credentials&client_id=' + key + '&client_secret=' + secret
})
As I mentioned in a comment, you shouldn't make the above request from a browser since it exposes the client secret.
Thanks to #Arun's recommendation of adding Content-Type, I am getting the right response now.
Also, for any other JavaScript newbies playing around with the petfinder API, this is the chain that I used to extract the token from the response:
fetch('https://api.petfinder.com/v2/oauth2/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'grant_type=client_credentials&client_id=' + key + '&client_secret=' + secret
}).then(response => response.json().then(data => ({
data: data,
status: response.status})
).then(function(res) {
console.log(res.status, res.data.access_token);
}));
I am trying to pass in a product number from my client to my server so I can save it to a database. I've tried almost 100 different ways to print out the "prod" variable but nothing is working.
I already have body-parser and other things included in my code. Is there some small thing I'm doing wrong? if so how should I edit my client file or server file to be able to pass in "prod" from the client to server.
As of right now if just says undefined
Client.js:
function addToCart(prod1) {
fetch( '/addToCart' , { method: ' POST ', body: ' prod= ' + prod1 });
}
server.js:
app.post("/addToCart", (req, res) => {
console.log(req.body.prod);
});
I expect whatever "prod" is, to be visible in my server file file when I console.log it out to the screen
Add application/json as header's content type and use JSON.stringify({yourKey:yourData}) as the body.
Client:
function addToCart(prod1) {
fetch( '/addToCart' , {
headers: { "Content-Type": "application/json" },
method: ' POST ',
body: JSON.stringify({prod : prod1 })
});
}
Server:
app.post("/addToCart", (req, res) => {
console.log(req.body.prod);
});
Why you don't try to send a json object instead a string?
data = {
prod: prod1
}
function addToCart(data) {
fetch( '/addToCart' , { method: ' POST ', body: JSON.stringify(data) });
}
The first problem I see here is that you donpt shot the content-type of your client request.
If you use for example
headers: { 'Content-Type': 'application/json' }
than the correct way to pass POST data is:
body: JSON.stringify({prod: prod1})
I have the below code on client side, on click event It sends a request server side node to get a token, then when token is returned from external url response. It passes that token onto the second ajax call to call a specific api route.
This all works great, but I want to logout the token after I get the response from a specific api route (using the token). So that after the response I don't have the token staying alive.
What would be a good way to accomplish this? My current solution is when the response for the specific api route is given, send a fetch request to /tokenrequest/logout to logout the token. But not sure if that is a correct or good way to do it.
getdata.addEventListener("click", function(e) { //simple button click to initiate api
e.preventDefault();
$.ajax({
method: "GET",
url: "/jdeapi",
error: function(request, status, error) {
console.log(error);
}
}).then(function(data) {
console.log(JSON.parse(data));
let rawData = JSON.parse(data);
var token = rawData.userInfo.token;
$.ajax({
method: "POST",
url: "/sendtojde",
data: {
token
}
}).then(function(data) {
console.log(data);
})
})
})
The node server side code is as follows for the token request
router.get('/jdeapi', function(req, res) {
let url = 'https://Aisserver:port/jderest/tokenrequest';
let data = {
username: 'username',
password: 'password',
deviceName: 'riolivApp'
}
fetch(url, {
credential: 'include',
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.text())
.then(text => res.json(text));
})
Then after the 2nd ajax call on client side, the server side call to fetch a specific api is as follows
router.post('/sendtojde', function(req, res) {
console.log(req.body.token);
let url = "https://Aisserver:port/jderest/poservice"
let data = {
token: req.body.token,
deviceName: 'riolivApp',
applicationName: "P4310",
version: "RMI0001"
}
fetch(url, {
credential: 'include',
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.text())
.then(text =>
res.json(text));
})
I have an application where we are generating a JWT token and passing that token in Header in the next api call.As a response of that, I should get a key.I am able to see the response through postman.I am using ReactJS in Front End and trying to achieve the same by passing the JWT token in Header while doing the api call but facing some issues.
My code-
getKey() {
let postData = {
vin: "5678",
id: "abc12",
};
axios({
method: "post",
url: "http://localhost:8080/generateKey",
headers: {
"Content-Type": "application/json"
},
data: postData
})
.then(function(response) {
setKey(response.data.key);
})
.catch(function(error) {
console.log(error);
getKeyError();
});
}
memberAuth() {
var self = this;
axios({
method: "GET",
url: "http://localhost:8080/authenticateMember",
headers: {
"Content-Type": "application/json",
"Authorization": localStorage.setItem()
},
data: {
"id":"xyzzy",
"password":"abc"
}
})
.then(function(response) {
//to do
}
I am trying to save the generated token (valid for 30mins) in a localStorage/SessionStorage but not sure if this is the right way. Can someone tell me where am I going wrong.
Create instance of your axios,
const agent = axios.create({
baseURL: config.api_url,
transformRequest: [transformRequest],
transformResponse: [transformResponse],
headers: { 'Content-Type': 'application/vnd.api+json' },
});
And then call this function to set headers dynamically
agent.defaults.headers.common['Authorization'] = `JWT ${localStorage.getItem('token')}`;
Then call methods of your axios instance to make API calls
agent.get(`${endpoint}search`, { params }),
agent.post(`${endpoint}search`, JSON.stringify(body)),