This question already has an answer here:
Why express server receives front end data as undefined?
(1 answer)
Closed 12 days ago.
The community reviewed whether to reopen this question 12 days ago and left it closed:
Original close reason(s) were not resolved
I'm trying to build a react/node application and I was trying to pass a value which I get from user input to the nodejs api to call a separate api (Instagram API)
I want to attach an object to req.body from React app. I want to do something like this:
app.get('/hashtags', (req,res) => {
console.log(req.body);
console.log(req.body.tag);
});
This is my responsible react app code for the above node request:
handleChange(e){
const searchtag = 'hello';
fetch('/hashtags', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
tag: searchtag,
}),
})
}
I'm calling handleChange function when I click a button.
As for the above code I need my node api to call /hashtags with req.body.tag = 'hello' (as I'm passing 'hello' from reactjs).
But this gives me the following error:
Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.
If this can't be done this way: How can I attach an object to node api req.body from my react application?
If you want to pass string search tag why you are passing it in body. As per REST pass it in the url like this
handleChange(e){
const searchtag = 'hello';
fetch('/hashtags/' + searchtag, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
),
})
}
axios({
method: 'GET',
url: `${api.course}`,
headers: { Authorization: `Bearer ${localStorage.getItem('accessToken')}` },
data:{'category': "Design"}
})
Related
I am making a post API call using fetch in my react app (redux-thunk) and getting a '401-Unauthorized' error. but, I made the same post request in postman with the same Authorization token and it returned a successful response.
While trying multiple fixes, I found that I am able to post requests successfully using the npm request library in a standalone node application. Hence, I assume that I am missing something while making the call using fetch in react application. Unfortunately, I cannot use the request library in my react application as it is deprecated and throwing unwanted errors.
Can someone please help me fix this issue? I added my code below:
export const addTodoAsync = createAsyncThunk(
"todos/addTodoAsync",
let token = '22e745f508990f40c97feccf5cf3397f7fbe0ae96f6b7baf051fccbcbb8267df';
async (payload) => {
const response = await fetch('https://gorest.co.in/public/v1/todos', {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
},
body: {user_id: '6000', title: 'wakeup', status: 'pending', due_on: '2022-07-22T10:40:36.630Z+10:40'}
});
if (response.ok) {
let todo = await (response.json()).data;
return { todo };
}
}
);
change :
body: {user_id: '6000', title: 'wakeup', status: 'pending', due_on: '2022-07-22T10:40:36.630Z+10:40'}
to :
body: JSON.stringify({user_id: '6000', title: 'wakeup', status: 'pending', due_on: '2022-07-22T10:40:36.630Z+10:40'})
Already checked the endpoint with Insomnia and is working fine, but when trying to connect with the backend from the client there is some kind of problem. The connection between the client and the server is done this way:
const uri = `${basePath}/${baseVersion}/sign-up`;
const params = {
method: "POST",
body: JSON.stringify(data),
header: {
"Content-Type": "application/json"
}
};
And if I show in the console params object this is what is inside it:
enter image description here
Just to clarify, there isn't a CORS problem as I am using a Google Chrome extension for it.
This is the response of the fecth:
enter image description here
Is your problem not receiving a response from the server in the promise? If so, that is because there is no code in your snippet that actually returns the data. (Sorry if I misidentified the problem, I don't have the ability to comment)
const uri = `${basePath}/${baseVersion}/sign-up`;
async function fetchPost(data = {}) {
var response = await fetch(uri,
method: "POST",
mode: "cors",
header: {
"Content-Type": "application/json"
},
referrerPolicy: "strict-origin-when-cross-origin" //you can replace that with anything you want depending on the situation
body: JSON.stringify(data)
});
// if you're expecting the response to be json, use the below, but if you want it in text, then do response.text, etc.
return response.json();
}
fetchPost();
This question already has answers here:
How to call GraphQL API from Node.js/Express server?
(2 answers)
Closed 2 years ago.
I am trying to connect to a website and they have given me :
Url: https://api.demo...
headers:"x-api-key" and "x-api-user"
I do not know how to make the connection with them,I tried the code below:
const query = `
query {
some query here
}
`;
const url = ``
const opts = {
method: "POST",
headers: { "x-api-key": ,
"x-api-user": , },
body: JSON.stringify({ query })
};
Is this the right way? when I run it npm start=> App Crashes I am new to javascript and I dont even know how to make the search in google,can someone please guide me to a tutorial,link or please respond with the right way?
Thank you for your understanding
You can do it using the fetch call.
const query = `query {
Some query
}`;
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query
})
})
.then(r => r.json())
.then(data => console.log('data returned:', data));
This question already has answers here:
How do I POST a x-www-form-urlencoded request using Fetch?
(17 answers)
Closed 4 years ago.
I have written a JS function to post categoryId and shopId and page:0 to an api and this is my funciton :-
getInsideMenu(categoryid,shopid){
var formBody = [];
var details={
'categoryId':categoryid,
'shopId':shopid ,
'page':'0'
};
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
return fetch(
`${serverAddress}/api/shopProducts`,
{
method: 'POST',
body: formBody,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
).then((res)=>(res.json()))
},
But I'm getting null .I suppose the function is not defined properly. What can be done to fix it. It works well in POSTMAN.
[![this is in postman how I send][1]][1]
You're building an array of encoded name/value pairs and passing that directly as the body of the POST. But fetch doesn't accept an array in that parameter.
The minimal change to your code would be to join the array using & as the separator:
return fetch(
`${serverAddress}/api/shopProducts`,
{
method: 'POST',
body: formBody.join("&"), // <===== here
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
). /* etc */
Alternately, use FormData, as this is exactly what it's for: :-)
getInsideMenu(categoryid,shopid){
var formBody = new FormData();
formBody.set("categoryId", categoryid);
formBody.set("shopId", shopid);
formBody.set("page", "0");
return fetch(
`${serverAddress}/api/shopProducts`,
{
method: 'POST',
body: formBody,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
).then((res)=>(res.json()));
}
(Depending on your needs, you might use set or append. The above uses set.)
Side note 1:
This line:
).then((res)=>(res.json()));
...doesn't need most of those ():
).then(res => res.json());
Side note 2:
Don't forget to check for success; failing to do so is a common pitfall when using fetch. fetch doesn't reject on HTTP error (like 404 or 500). If you want to reject on HTTP error, you have to do it yourself:
return fetch(/*...*/)
.then(res => {
if (!res.ok) {
throw new Error(res.status);
}
return res;
})
.then(res => res.json());
Read this answer
You have to insert at least formBody = formBody.join("&"); after the loop.
I am new to ReactJS and I am trying to build this app that need to use mailchimp so the user can subscribe for newsletter. I need to make a request using axios? can someone guide me through this? where do i put my api key? Did I do it correct in the bellow code? i put my mailchimps username in 'username' and my apikey in 'xxxxxxxxxxxxxxxxxxx-us16', however, i got the 401 error saying Unauthorized, BUT my console did say Fetch Complete: POST and caught no error.
import React, {Component} from 'react';
import './Subscribe.css';
class Subscribe extends Component {
sub = () => {
let authenticationString = btoa('username:xxxxxxxxxxxxxxxxxxx-us16');
authenticationString = "Basic " + authenticationString;
fetch('https://us16.api.mailchimp.com/3.0/lists/xxxxxxxxx/members', {
mode: 'no-cors',
method: 'POST',
headers: {
'Authorization': authenticationString,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email_address: "somedude#gmail.com",
status: "subscribed",
})
}).then(function(e){
console.log('complete')
}).catch(function(e){
console.log("fetch error");
})
};
render () {
return(
<div>
<button onClick={this.sub}> subscribe </button>
</div>
);
};
};
In the documentation, the curl example uses the --user flag. Using this to convert curl commands to an equivalent js code, you need the 'auth' property on the option object of the fetch to make it work.
fetch('https://us16.api.mailchimp.com/3.0/lists/xxxxxxxxx/members', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
email_address: "somedude#gmail.com",
status: "subscribed",
},
auth: {
'user': 'username',
'pass': 'xxxxxxxxxxxxxxxxxxx-us16'
})
})
It took me a while to get the syntax right for this. This is an example of a working request using nodejs in a server-side-rendered reactjs app using axios.
It appears "get" requests won't work for this method because of the 401 error: MailChimp does not support client-side implementation of our API using CORS requests due to the potential security risk of exposing account API keys.
However, patch, put, and post seem to work fine.
Example (using async / await)
// Mailchimp List ID
let mcListId = "xxxxxxxx";
// My Mailchimp API Key
let API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxx-us12";
// Mailchimp identifies users by the md5 has of the lowercase of their email address (for updates / put / patch)
let mailchimpEmailId = md5(values["unsubscribe-email-address"].toLowerCase());
var postData = {
email_address: "somedude#gmail.com",
status: "subscribed"
};
// Configure headers
let axiosConfig = {
headers: {
'authorization': "Basic " + Buffer.from('randomstring:' + API_KEY).toString('base64'),
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
try {
let mcResponse = await axios.post('https://us12.api.mailchimp.com/3.0/lists/' + mcListId + '/members', postData, axiosConfig)
console.log("Mailchimp List Response: ", mcResponse);
} catch(err) {
console.log("Mailchimp Error: ", err);
console.log("Mailchimp Error: ", err["response"]["data"]);
}
You can using the method described there: AJAX Mailchimp signup form integration
You will need to use JSONP otherwise you will get a CORS error.
If you use a modern environment (I mean not jQuery), you can achieve this method using a library like qs or queryString to transform your form data to an uri.
Your final url could look something like:
jsonp(`YOURMAILCHIMP.us10.list-manage.com/subscribe/post-json?u=YOURMAILCHIMPU&${queryString.stringify(formData)}`, { param: 'c' }, (err, data) => {
console.log(err);
console.log(data);
});
It's a bit hacky and I guess Mailchimp can remove this from one day to the other as it's not documented, so if you can avoid it, you'd better do.