I want to upload image in the nodejs server by graphql and formdata with axios and this is my way but not working , I think this problem is in append to form data but I can not find why or in axios fetch data
Code
let data = {
query: `
mutation Mutation($image: Upload!) {
multimedia(image: $image) {
status
message
token
}
}`,
variables: {
image: null,
},
};
let map = {
0: ["variables.image"],
};
const FormD = new FormData();
FormD.append("operation", JSON.stringify(data));
FormD.append("map", JSON.stringify(map));
FormD.append(0, element.file, element.file.name);
console.log(FormD);
await axios({
url: "/",
method: "POST",
headers: {
token: token,
"Content-Type": "multipart/form-data",
},
data: FormD,
onUploadProgress:ProgressEvent=>{
element.loaded=ProgressEvent.loaded/ProgressEvent.total*100
}
})
.then((response) => {
if (response.data.errors) {
const { message } = response.data.errors[0];
toast.error(message);
} else {
setLoadedFiles(tempLoadedFiles);
}
})
.catch((error) => {
console.log(error);
});
but the response is
response
{
"message": "Request failed with status code 400",
"name": "AxiosError",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {
"FormData": null
},
"headers": {
"Accept": "application/json",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyZjY3NWZiODkwNjY0N2RlZWRmMTM5ZiIsImlhdCI6MTY2MDg5NTgzMSwiZXhwIjoxNjYzNDg3ODMxfQ._5gmsMHD_HRokvoopKOit1n8YhG_sP3oR_OLRSXqZTo"
},
"baseURL": "http://localhost:4000/graphql",
"url": "/",
"method": "post",
"data": {}
},
"code": "ERR_BAD_REQUEST",
"status": 400
}
thanks for your answer
this problem solve in the nodejs server
fixed it in server by:
import express from "express";
import mongoose from "mongoose";
import Router from "./routes/index.js";
import User from "./models/users.js";
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.js'
import { ApolloServer } from "apollo-server-express";
import MakeSchema from "../api/models/index.js";
import { config } from "../config/index.js";
const app = express();
const Application = () => {
const ServerConfig = async () => {
const server = new ApolloServer({
schema: MakeSchema,
playground: true,
introspection: "production",
formatError(err) {
if (!err.originalError) {
return err;
}
const data = err.originalError.data;
const code = err.originalError.code || 500;
const message = err.message || "error";
return { message, data, code };
},
context: async ({ req }) => {
let check;
let user;
let userInfo;
await User.VerifyToken(req).then((val) => {
check = val;
});
if (check) {
user = await User.findById(check.id);
userInfo = await User.CheckUserInfo({
fname: user.fname,
address: user.address,
});
}
if (user) {
return { role: user.role, check, userInfo };
}
return { check, role: user };
},
});
await server.start();
**app.use(graphqlUploadExpress())
app.use(express.static('public'))
app.use('/public',express.static('public'))
await server.applyMiddleware({ app });**
app.listen(config.port, () => {
console.log(`Server run on port ${config.port}`);
});
};
const DatabaseConfig = () => {
mongoose.Promise = global.Promise;
mongoose.connect(config.database.url, config.database.options);
};
const Routes=()=>{
app.use(Router)
}
ServerConfig();
DatabaseConfig();
Routes();
};
export default Application;