I am trying to call the hasnode API to get blogs as the response, the body is in GraphQL. But I get this error in the Network Tab 'POST body missing. Did you forget use body-parser middleware?'
`
let query = `
{
user(username: "singhmona") {
publication {
posts{
slug
title
brief
coverImage
}
}
}
}
`;
let body = JSON.stringify({
query
});
axios
.post('https://api.hashnode.com/',
body,
{
'content-type': 'application/json',
})
.then(response => {
this.info = response;
console.log(response);}
)
`
I think you should try using fetch. I've had a tough one with axios when using it in node and I was finally able to get the api to work with fetch. Here is a snippet of what worked for me.
const getData = async() => {
const query = `
{
user(username: "misiochaabel") {
publication {
posts(page: 0) {
slug
title
brief
coverImage
}
}
}
}
`;
const response = await fetch('https://api.hashnode.com/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query }),
});
const data = await response.json();
console.log(data);
}
Related
Im trying to fetch an API using chaining with .then but I don't figure it out I try like:
async fetch() {
let path = this.$nuxt.context.route.path
this.response = await axios.get(
`/api${path}`,
{
headers: {
'X-AUTH-TOKEN': process.env.SECURE_TOKEN,
'Content-Type': 'application/json'
}
}
).then((res) => {
this.results = res.data.content.slice(0,40);
return results();
})
.then((res) => {
this.results2 = res.data.content.slice(20,40);
return results2();
})
},
For my API data load: when results is finish /results2 start to load, for using it with $fetchState.pending
What will be the best way of doing it? I'm trying to adapt the answer from here but no success so far.
This kind of code should be working fine
<script>
export default {
async fetch() {
this.response = await axios
.get(`/api${this.$route.path}`, { // faster than this.$nuxt.context.route.path
headers: {
'X-AUTH-TOKEN': process.env.SECURE_TOKEN,
'Content-Type': 'application/json',
},
})
.then((res) => { // ❌ this is useless because you're already using await above
const results = res.data.content.slice(0, 40)
return results()
})
.then((res) => { // ❌ this is useless because `slice` is NOT async
const results2 = res.data.content.slice(20, 40)
return results2()
})
},
}
</script>
Otherwise, I can also recommend a better approach overall, using async/await and not mixing it with .then at all, like this
<script>
export default {
async fetch() {
const response = await axios.get(
`/api${this.$route.path}`,
{
headers: {
'X-AUTH-TOKEN': process.env.SECURE_TOKEN,
'Content-Type': 'application/json',
},
}
)
const results = response.data.content.slice(0, 40)
const results2 = results.data.content.slice(20, 40)
},
}
</script>
PS: note that some things are not async, hence do not need await (or .then at all).
It can even be shorten to the following
<script>
export default {
async fetch() {
const response = await this.$axios.$get( // 👈🏻 using the shortcut $get
`/api${this.$route.path}`,
{
headers: {
'X-AUTH-TOKEN': process.env.SECURE_TOKEN,
'Content-Type': 'application/json',
},
}
)
const results = response.content.slice(0, 40) // 👈🏻 no need for `.data` here
const results2 = results.content.slice(20, 40) // 👈🏻 same here
},
}
</script>
Thanks to the shortcuts available with the axios module that you should be using anyway.
As of why you should use async/await, it's just more lisible and available everywhere already (IE is dead). Here is some more info about the whole async/await thing: https://javascript.info/async-await
Far prettier than this kind of syntax (also named callback hell)
i'm trying to send a request to the backend which uses headers, please how can i add the headers
this is my script tag
<script>
import axios from "axios";
export default {
data: () => ({
fullName: "",
streetAddress1: ""
}),
created() {
//user is not authorized
if (localStorage.getItem("token") === null) {
this.$router.push("/login");
}
},
methods: {
async onAddAddress() {
const token = localStorage.getItem("token");
headers: {
"Content-Type": "application/json",
Authorization: "Bearer" + token,
"x-access-token": token
}
try {
let data = {
fullName: this.fullName,
streetAddress: this.streetAddress1
};
const response = axios
.post("http://localhost:5000/api/addresses", data)
.then(res => {
console.log(res);
});
console.log(response);
} catch (error) {
console.error("error >>", error);
}
}
}
}
this code gives me an error, please how can i go about this
There are a few problems with your code. For instance you do not define headers as a variable and you do not add it to your axios request as a third argument. I think you need something like this:
async onAddAddress() {
const token = localStorage.getItem("token");
/// define headers variable
const headers = {
"Content-Type": "application/json",
Authorization: "Bearer" + token,
"x-access-token": token
};
let data = {
fullName: this.fullName,
streetAddress: this.streetAddress1
};
try {
/// config as the third argument.
conts result = await axios.post("http://localhost:5000/api/addresses", data, { headers });
console.log(result);
}
catch (error) {
console.error("error >>", error)
}
}
For async/await to work, you need to add await in front of the axios call.
Hope this helps.
How do I pass a file upload as a graphql mutation variable? Submitting this test gives me a 400 bad request with this error:
Variable \"$thumbnailFile\" got invalid value {}; Upload value invalid.
I am using graphql-upload. I am sending my queries like this:
async function graphQLFetch(query, variables = {}){
const response = await fetch('/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables })
});
const body = await response.text();
const result = JSON.parse(body);
return result.data;
}
In my react component:
handleThumbnailChange(event){
const thumbnailFile = event.target.files[0];
const query = `mutation addThumbnailTest($thumbnailFile: Upload){
addThumbnailTest(thumbnailFile: $thumbnailFile){
thumbnailSrc
}
}`;
const data = await graphQLFetch(query, {
thumbnailFile
});
}
My schema:
scalar Upload
type Mutation {
addThumbnailTest(thumbnailFile: Upload): String
}
My server is setup like the following:
const { ApolloServer } = require('apollo-server-express');
const { GraphQLUpload, graphqlUploadExpress } = require('graphql-upload');
const express = require('express');
const resolvers = {
Upload: GraphQLUpload,
Mutation: {
handleThumbnailChange: handleThumbnailChange,
}
}
const server = new ApolloServer({
typeDefs: fs.readFileSync(path.join(__dirname, 'schema.graphql'), 'utf-8'),
resolvers
});
async function installHandler(app){
await server.start();
server.applyMiddleware({ app, path: '/graphql' });
}
const app = express();
(async function start(){
try{
// Install GraphQL API Handler
app.use(graphqlUploadExpress());
await installHandler(app);
I had to submit the query as form data and without the { 'Content-Type': 'application/json' } header
async function graphQLFetch(query, variables = {}, multipart = false){
let request;
if(multipart){
const data = {
operations: JSON.stringify({
query,
variables: {
...variables,
file: null
}
}),
map: JSON.stringify({
'0': [
'variables.file'
]
})
};
const requestBody = new FormData();
for(const name in data) {
requestBody.append(name, data[name]);
}
requestBody.append('0', variables.file);
request = {
method: 'POST',
body: requestBody
}
} else {
request = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables })
}
}
const response = await fetch('/graphql', request);
const responseBody = await response.text();
const result = JSON.parse(responseBody);
return result.data;
}
I want to upload photos with React Native. My API attempt from Postman resulted in a positive.
But React Native didn't make it.
React Native function
uploadPhoto = async response => {
const data = new FormData();
data.append("image", {
uri: response.uri,
type: response.type,
name: response.fileName,
length:response.fileSize
});
const config={
headers:{
'Content-type':'multipart/form-data'
}
}
axios
.post('https://localhost:44337/api/values',JSON.stringify(data),config)
.then(response=>{
console.log(response);
})
.catch(error=>{console.log(error);})
};
Asp.net Core side
[HttpPost]
public IActionResult Post([FromForm]PhotoModel bookData)
{
//installation codes
return Ok();
}
Model
public class PhotoModel
{
public IFormFile image { get; set; }
}
Result:Network Error
You can try in react native code.
Hope helpful for you.
export const uploadImages = async (formData) => {
try {
let response = await axios({
url: urlUploadImages,
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, PUT, OPTIONS, DELETE',
'Access-Control-Allow-Headers': 'Access-Control-Allow-Methods, Access-Control-Allow-Origin, Origin, Accept, Content-Type',
'Accept': 'application/x-www-form-urlencoded',
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + global.TOKEN || 'Bearer ' + await AsyncStorage.getItem("#loggedInUserID:token"),
},
data: formData,
});
console.log('uploadImages API response', response)
if (response.status === 401) {
return global.UNAUTHORIZE;
} else {
// let json = await response;
if (response.status === 200) {
return response.data;
} else {
return global.FAIL;
}
}
} catch (error) {
console.log('Upload Failed', error);
}
};
You don't have to change from form data back to JsonString. Send it right away.
.post('https://localhost:44337/api/values',data,config)
Remove json.stringify and verify that you set right values:
const form = new FormData();
form.append('image', {
uri: "file:///...",
type: 'image/jpg',
name: 'image.jpg',
});
I need to fetch data from pass parameter in below format, because when test in Postman then only this format gives response.
"json": {"model":"DB11 AMR","modelyear":"2019","locale":"AA"}
Can you please help to fetch data from below server url.
https://vhapp.azurewebsites.net/myAMLModelSelection
Below is my code
var url = 'http://vhapp.azurewebsites.net/myAMLModelSelection'
try {
let response = fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"json" : { "locale": "AA", "model" : "DB11 AMR", "modelyear" : "2019" }
})
})
.then(res => res.text()) // convert to plain text
.then(text => {
console.log(text)
alert(text)
var res = text.substring(1, text.length-2);
var obj = JSON.parse(res);
alert(obj.cars[0].name)
})
.catch((error) => {
console.error(error);
});
} catch (errors) {
console.log(errors);
}
Here is my response which i need
({"cars":[{"name":"DB11 AMR","content":{"guide":"http://cdntbs.astonmartin.com/360ss/OwnersGuides/KY53-19A321-AC.pdf","assets":[{"intAssetId":"115","intVehicleId":"1","strType":"pdf","strName":"Accessories Brochure","strDescription":null,"strLocation":"http://cdntbs.astonmartin.com/360ss/iPad/myaml/brochures/Accessories Brochure English - 706435-PK.pdf","intVersion":"1","intOrder":"1"}]}}]});
You can fetch the data using JS fetch API.
export async fetchMyData(){
try{
let f = await fetch('https://vhapp.azurewebsites.net/myAMLModelSelection',{method:'GET'})
let data = await f.json();
return data;
}catch(err){
console.log(err)
}
}
And Call this method in your component like:
import {fetchMyData} from './file_name'
fetchMyData().then((response)=>{console.log(response)})