I am trying to make a POST request to my graphql server that I have running on localhost:4000. To get my users I was using
getUsers(){
var query = `{users(id:""){username}}`
fetch('http://localhost:4000/graphql', {
method:'POST',
headers: {
'Content-Type' :'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query,
})
})
.then(res => res.json())
.then(res => console.log('data returned', res))
this wasn't working so I made a curl request to see what was wrong,
curl -X POST http://localhost:4000/graphql -H "Content-Type: application/json "-d "{"query": "{users(id:""){username}}"
After I ran this I kept getting,
Unexpected token q in JSON at position
After looking up this issue on google first I found a tutorial that I thought might be able to help. Following the tutorial I changed my code to
getUsers(){
var query = `{users(id:""){username}}`
fetch('http://localhost:4000/graphql', {
method:'POST',
headers: {
'Content-Type' :'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query,
})
})
//.then(r => r.json())
.then(res => res.text())
.then(text => console.log('data returned', text))
which still didn't log anything.
So i ran one last curl to attempt to solve this problem
curl -X POST http://localhost:4000/graph0ql -d "{"query": "{users(id:""){username}}"
which kept returning
{"errors":[{"message":"Must provide query string."}]}
Now I'm stuck and I don't know what to try next.
I checked the query string and it gives me the intended response in graphiql and the url is correct as well. My angular frontend server (from which I am making this request) is running on localhost:4200
Ok I feel pretty dumb. I didn’t call my function correctly. It works all that’s left is to actually use the data
The issue is how you're passing the query object. Try to update it into something like:
getUsers(){
var query = `query getUsers { users(id:"") { username } }`
fetch('http://localhost:4000/graphql', {
method:'POST',
headers: {
'Content-Type' :'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query: query,
})
})
//.then(r => r.json())
.then(res => res.text())
.then(text => console.log('data returned', text))
}
Related
In my node app, I'm trying to make a GET request to another server by Axios:
axios.get(`http://my-domain:2095/server/get-status`)
.then(result => { console.log(result.data) });
console.log shows me something like this (which is supposed to be JSON):
\x1F�\b\x00\x00\x00\x00\x00\x00\x03tα\x0E� \x14\x05�\x7F�3\x03/
��\f��8���\x12�\x04i\x17¿�j��g8\x15{Z%Ep�*��(9�\r<U�\x02\x06\r�x\x07���\��E0�^[OD�j��U�\x7F���r�)���mV�a�\x1D<�M�\x15R\x19���xc�\x04\x00\x00��\x03\x00\x02d&��\x00\x00\x00
The output is OK when I use ip:port in address. But not with domain:port.
Also The response of http://my-domain:2095/server/get-status is OK when I enter it in browser and Postman.
So what is the problem with Axios?
In axios v1.2.1, it fixed this error.
You need to add Accept-Encoding with application/json in axios.get header.
code in v 1.2.0
axios.get(`http://my-domain:2095/server/get-status`,
{
headers: {
'Accept-Encoding': 'application/json',
}
})
.then(result => { console.log(result.data) });
OR fixed in v1.2.1
axios.get(`http://my-domain:2095/server/get-status`)
.then(result => { console.log(result.data) })
I am trying to send a request using axios post with basic authorization. It is working fine with postman but not working when I try to send via code.
axios.post(`my-url`, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic **KEY_HERE**',
},
data: {
'id': 'event_order',
'date': '2021-09-09'
}
}).then(async (response) => {
console.log(response.data)
})
It is returning 401 Unauthorized. But, it works as excepted when I call it via Postman:
Postman Setup Image
Did you add your domain to whitelist in your cors module? If not:
app.use(cors({ origin: "PROTOCOL://DOMAIN:PORT", credentials: true }));
edit: Ok, sorry, I was confused and thought you were sending a frontend axios post request to your own NodeJS server. If possible, could you be more precise. But try passing in your headers/auth as the third argument-- since you're passing in everything in the second argument, the API is not parsing out your headers since its part of the data parameter.
const data = {
'id': 'event_order',
'date': '2021-09-09'
}
axios.post(`my-url`, data, {
headers: {'Content-Type': 'application/json'},
auth: {
username: "YOUR_USERNAME",
password: "YOUR_PASS"
}
})
.then(async (response) => {
console.log(response.data)
})
Also try and post the network errors, if you can.
Can anyone spot any problems that may explain why the api client is giving me the forbidden error? I know the credentials are correct, as GET requests w the same info in the url work find.
Thank you in advance
app.get('/translate', (req, res) => {
var textToTranslate = "Hello friend"
const targetLanguage = "ES"
var link = `https://api-free.deepl.com/v2/translate`
var options =
{
method: 'POST',
headers: {
"Host": 'api-free.deepl.com',
"Content-Length": 54,
"Content-Type": 'application/x-www-form-urlencoded',
"User-Agent": "YourApp",
"Accept": "*/*",
},
body: JSON.stringify({
'auth_key': deeplAccessCode,
'text': textToTranslate,
'target_lang': targetLanguage
}),
}
return fetch(link, options)
.then((response) => {
console.log(response)
return response.json(); //Transform http body to json
})
.then((json)=> {
res.send(json) //return json to browser
})
.catch(e => {
console.log(e)
return res.sendStatus(400);
});
})
It's probably failing because you're setting your Content-Type of your body to be application/x-www-form-urlencoded (which is correct as per the DeepL API specification) but then you provide a JSON body (which would require content type to be application/json).
You need to provide a URL-encoded body instead, like the part you can also append to the URL after the ?. See also this answer on SO.
I'm working on my first app right now which I created in react native for the front end and using Node JS as a backend and mongodb for the database.
I'm trying to implement register form for my user but I don't really know how to do this with the state because it keeps saying cannot evaluation this.state.name.
What I want to do is a POST request using fetch api to register an account it works using Postman so the error come from my front end.
So what I do is I create my function to do that but I want the body to represent the value the user typed in the different field which I store in the state when you'll see the code it will be clear.
If I use the state it does not work however if I put some value directly in my function it works.
This first thing is my function with the fetch API if I do this it does not work, below is how I get the state of each field (see the )
clickthebutton = () =>{
//var data = this.state
fetch('http://localhost:5050/api/new/register',{
method:'POST',
headers : {'Content-Type': 'application/json'},
body : {
name:this.state.name,
age:this.state.age,
password:this.state.password,
email:this.state.email
},
})
}
<Input
label="Your email address"
placeholder="yo#gmail.com"
onChangeText={(text)=> this.setState({email:text})}
value={this.state.email}
>
My state looks like this :
this.state={
email:null,
password:null,
name:null,
age:null,
dataImage:null
}
I would like to send the body, if I do body : this.state it does not send anything when I do a console.log(req.body) on my server it shows an empty object.
Thanks for any help
EDIT : Problem fixed, my function was not referring to my class.
First of all you need a correct element for your email and password inputs, for example (for email):
<TextInput
value={this.state.name}
keyboardType={'email-address'}
placeholder="Your email address"
onChangeText={text => this._onEmailChange(text)}
/>
you also need a function to update the name value (you will need a similar function to update any value coming from a TextInput element)
_onEmailChange = text => {
this.setState({ name: text });
};
Then you can prepare your request as follow
fetch('http://localhost:5050/api/new/register', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.state.name,
password: this.state.password
...
}),
})
.then(response => response.json())
.then(responseJson => {
// do what you want with the response here
})
.catch(error => {
console.error(error);
});
You have specified in the header that you send in json format when you send. When sending to the server, you must convert to jsonString.
fetch('http://localhost:5050/api/new/register', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name:this.state.name,
age:this.state.age,
password:this.state.password,
email:this.state.email
}),
});
Ok You can try use Formdata
let formdata = new FormData();
formdata.append("name", this.state.name);
formdata.append("age", this.state.age);
formdata.append("password", this.state.password);
formdata.append("email", this.state.email);
fetch('http://localhost:5050/api/new/register', {
method: 'POST',
headers: {
"Content-Type": "multipart/form-data"
},
body: formdata
})
.then(res => res.json())
.then(reponse => {
console.log(reponse)
})
.catch(error => {
console.error(error);
});
After getting all form-data in your state you have two options to make a request to backend.
Either set Content-Type As application/text or remove header.
fetch('http://localhost:5050/api/new/register',{
method:'POST',
headers : {'Content-Type': 'application/text'},
body : {
name:this.state.name,
age:this.state.age,
password:this.state.password,
email:this.state.email
},
})
So far I have this command to use in the terminal to make a GET request to readme.io api
curl https://dash.readme.io/api/v1 -X GET -u API_KEY:
PASSWORD VALUE is empty, the curl command works just fine in the terminal.
How do I do that with node.js
I have this.
const options = {
method: 'GET',
headers: {
'Authorization': 'Basic API_KEY:'
}
};
fetch('https://dash.readme.io/api/v1', options)
.then(res => res.text())
.then(body => console.log(body))
.catch(err => console.log('ERROR', err))
but it returns:
{"error":"Unauthorized","errors":null}
Can you please tell me what part did I mistaken?
Thanks in advance.