I’m sending some data to the backend to create a post. It consists of some strings and arrays. When I test the query through graphiQL it works fine, but when I send the request on the frontend it returns
“Syntax Error: Expected Name, found “:”.
at Proxy.addPost (webpack-internal:///./node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./src/components/NewPost.vue?vue&type=script&lang=js:71:15)”
I am using graphql-http to run GraphQL. The backend is Node + Express and Sequelize is managing SQL queries.
The frontend is Vue.js 3
Here is the frontend request
async addPost(event) {
event.preventDefault();
const form = new FormData(event.target);
const title = form.get("title");
const abstract = form.get("abstract");
const body = form.get("body");
const id = JSON.parse(localStorage.getItem("user")).id;
const tags = [...document.querySelectorAll(".selected-tag")];
const tagsContent = [];
for (let i = 0; i < tags.length; i++) {
tagsContent.push(tags[0].innerText);
}
if (!title.length) {
console.log("Please add a title.");
return;
}
if (!body.length) {
console.log("Please add content to your post.");
return;
}
if (!tagsContent.length) {
console.log("Please add at least one tag.");
return;
}
const QUERY = {
query: `
mutation{
addPost(addPostInput: {title: "${title}", abstract: "${abstract}", body: "${body}", tags: ${tagsContent}, images: ${[]}, id: ${id}}){
message
data {
title
abstract
body
tags
images
}
}
}
`,
};
const response = await fetch("http://localhost:3000/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(QUERY),
});
const responseData = await response.json();
if (responseData.errors) {
console.log(responseData.errors);
throw new Error(responseData.errors[0].message);
}
const post = responseData.data;
},
},
GraphQL schema
const { buildSchema } = require("graphql");
module.exports = buildSchema(`
type AuthData{
token: String!
id: Int!
}
type Message{
message: String!
data: PostData!
}
type User{
name: String!
picture: String
posts: [PostData]
}
type PostData{
title: String!
abstract: String!
body: String!
images: [String]
tags: [String]
}
input postInput{
title: String!
abstract: String!
body: String!
images: [String]
tags: [String]
id: Int!
}
input signupData{
name: String!
email: String!
password: String!
confirm: String!
}
type RootQuery{
getUser(id: Int!): User!
login(email: String!, password: String!): AuthData!
}
type RootMutation {
signup(signupInput: signupData): AuthData!
addPost(addPostInput: postInput): Message!
}
schema {
query: RootQuery
mutation: RootMutation
}
`);
addPost resolver
addPost: async ({ addPostInput }) => {
const title = addPostInput.title;
const abstract = addPostInput.abstract;
const body = addPostInput.body;
const tags = addPostInput.tags;
const images = addPostInput.images;
const id = addPostInput.id;
const user = await User.findByPk(id);
if (!user) {
console.log("Error fetching user.");
return;
}
await user.createPost({
title: title,
abstract,
body,
tags: JSON.stringify(tags),
images: JSON.stringify(images),
});
return {
message: "Success",
data: {
title,
abstract,
body,
tags,
images,
},
};
},
the graphQL server
const express = require("express");
const { createHandler } = require("graphql-http/lib/use/express");
const { ruruHTML } = require("ruru/server");
const graphqlSchema = require("./graphql/schemas");
const graphqlResolver = require("./graphql/resolvers");
const sequelize = require("./database");
const User = require("./models/user");
const Post = require("./models/post");
const app = express();
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PUT, PATCH, DELETE"
);
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
if (req.method === "OPTIONS") {
return res.sendStatus(200);
}
next();
});
app.use(
"/graphql",
createHandler({
schema: graphqlSchema,
rootValue: graphqlResolver,
formatError(err) {
if (!err.originalError) {
return err;
}
const data = err.originalError.data;
const message = err.message || "An error occurred.";
const code = err.originalError.code || 500;
return { message, status: code, data };
},
})
);
app.get("/", (_req, res) => {
res.type("html");
res.end(ruruHTML({ endpoint: "/graphql" }));
});
Post.belongsTo(User, { constraints: true, onDelete: "CASCADE" });
User.hasMany(Post);
sequelize
.sync()
.then(() => {
app.listen(3000, () => console.log("Server running on port 3000"));
})
.catch((err) => console.log(err));
I’ve already researched the error and all of them were to a wrong syntax, but I’ve already looked through my code and didn’t find anything. Besides, as mentioned above, the query does work when sent through graphiQL, it’s throwing an error when the request comes from the backend. I even copied the exact query from graphiQL but it still didn’t work.
Emerson Lima is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.