GithubHelp home page GithubHelp logo

jaydenseric / apollo-upload-examples Goto Github PK

View Code? Open in Web Editor NEW
428.0 13.0 112.0 5.04 MB

A full stack demo of file uploads via GraphQL mutations using Apollo Server and apollo-upload-client.

JavaScript 99.48% CSS 0.52%
react apollo graphql nextjs koa prettier babel eslint mjs nodejs

apollo-upload-examples's People

Contributors

danielpdev avatar jaydenseric avatar michaelmerrilltest avatar mike-marcacci avatar samcoenen avatar savepointsam avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

apollo-upload-examples's Issues

Runtime error: Unexpected token < in JSON at position 0

Hi, there! I'm having trouble integrating the apollo-upload-client into my app. I keep getting the error in the title above when uploading a file, so for good measure I've cloned this repo and just ran it (both the app and api). Same error as in my own app, the field 'operations' is present in the app from the repo and in my own.

Is this repo out of date? or am I doing wrong and how can I find out where the issue is?

Thank you in advance!

Unhandled Runtime Error ApolloError: Failed to fetch

Hello, I would greatly appreciate it if someone could direct me to where I might find a solution for this issue.. I tried to upload a png. photo but got this message: "Unhandled Runtime Error ApolloError: Failed to fetch"

ApolloError

I have node18.11.0 and NPM 18.19.2..

this is what the terminal is showing when starting the app

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info - Loaded env from C:\Users\jav83\OneDrive\Documents\apollo github examples\apollo-upload-examples\app.env
info - Disabled SWC as replacement for Babel because of custom Babel configuration ".babelrc" https://nextjs.org/docs/messages/swc-disabled
event - compiled client and server successfully in 658 ms (475 modules)
wait - compiling /_error (client and server)...
event - compiled client and server successfully in 126 ms (476 modules)
wait - compiling / (client and server)...
event - compiled client and server successfully in 175 ms (534 modules)
(node:14568) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use node --trace-warnings ... to show where the warning was created)
warn - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/messages/fast-refresh-reload

Multiple params causing issues

Using apollo client to send a request seems to be having issues when there are multiple params. This is the request its sending out

-----------------------------404023721040812881092308315507
Content-Disposition: form-data; name="operations"

{"variables":{"input":{"foodId":"f16b3a8e-dcf7-43f3-bede-d3a51c0fdeba"},"file":{"image":null}},"query":"mutation ($input: SetImageInput!, $file: Upload!) {\n  foods {\n    setImage(input: $input, file: $file) {\n      food {\n        image {\n          id\n          downloadUri(expiration: 60)\n          __typename\n        }\n        attachments {\n          fileName\n          id\n          downloadUri\n          __typename\n        }\n        __typename\n      }\n      __typename\n    }\n    __typename\n  }\n}\n"}
-----------------------------404023721040812881092308315507
Content-Disposition: form-data; name="map"

{"1":["variables.file.image"]}
-----------------------------404023721040812881092308315507
Content-Disposition: form-data; name="1"; filename="imageUploadIcon.png"
Content-Type: image/png

and this is the error I am getting back


{
"errors": [
{
"message": "Type 'Microsoft.AspNetCore.Http.IFormFile' does not contain a constructor that could be used for current input arguments. (Parameter 'type')",
"path": {
"$id": "1",
"$values": [
"foods",
"setImage"
]
},
"extensions": {
"code": "ARGUMENT",
"codes": [
"ARGUMENT"
]
}
}
],
"data": {
"foods": {
"setImage": null,
"__typename": "FoodMutation"
}
}
}

It seems to work find until there is an extra piece of non file data to be sent up. The request works when it is setup manually just using fetch instead of the apollo client but runs into issues here.

BadRequestError when upload file with cookies

When I use apollo-upload-examples with express and redis with cookie session, I can't upload files.

The message error is:

BadRequestError: Missing multipart field ‘operations’ (https://github.com/jaydenseric/graphql-multipart-request-spec).

I have created a fork of the example project to simulate the problem, you can see it in:

https://github.com/JMoldes/apollo-upload-examples/tree/error-with-express-redis

The changes that I have made are:

  • Install the modules express, apollo-server-express, connect-redis-sessions and cookie-parser
  • Modify server.mjs to use express, and use the middleware connect-redis-sessions, and create a test session when upload the first file
  • Modify _app.js for add credentials: 'include' to createUploadlink

When I execute `npm run dev' for api and app, (previously I have to install redis ...), the first file I upload is ok, because I have not sent any cookies yet,

But after the first file is sent, te api sent a cookie to client, and when I upload the sencod file the Api show the next message:

BadRequestError: Missing multipart field ‘operations’ (https://github.com/jaydenseric/graphql-multipart-request-spec).

If I comment the line 22: app.use(fnCRS) the file upload ok.

image

Why can not I upload files with express and redis using session cookies

Sync async behavior

I don't fully understand the sync/async part.
There is 2 differents behaviors but where can I change it ?

I tried this example and the behavior surprises me. It seems it's neither sync nor async.

  • Resolver is called
  • ReadStream is created on /tmp/file which is still uploading
  • pipe writeStream on fs is called between 1 and 4 times max.
  • Then it waits to fully upload the file on /tmp
  • Then finally fs writes the rest of the file

graphqupload

You can see that the the write stream is stuck at 9.7K while uploading readStream in /tmp is already at 1.1G and it goes on until totally upload the file.

Did I miss something ? Is it a apollo problem or my server. Like something with max memory used per process ?

Read the existing data in the "upload" folder

Hello @jaydenseric

Thank you for your work. I can upload the files and then read them with query but when I started to use your package I put some files in the "upload" folder and then I tried to read them with query, but the answer was empty []. But when I upload the files with mutation, I could read them with query.

Why server get upload.file.stream of undefined

client send a graphql like this:
image
and the image msg like this:
image
but the server get the file only has a uid props after used 'apollo-upload-server'
image
but your demo has got the props(stream, filename, mimetype, encoding) in file prop.

why i cannot get those props in file prop

Mocking in tests.

Are you able to provide an example of testing the File upload mutations via the MockedProvider from react-apollo/test-utils?

I cannot get the mocks to match because the variable is a File, which I cannot add to the mock variables.

e.g.
Assuming a simple File upload like this one named input

https://github.com/jaydenseric/apollo-upload-client#file

import gql from 'graphql-tag';
import { MockedProvider } from 'react-apollo/test-utils';
import { fireEvent, render } from '@testing-library/react';

import Input from '../Input';

export const IMAGE_UPSERT = gql`
  mutation ImageUpload($file: Upload!) {
    imageUpload(file: $file) {
      image {
        id
        alt
        src
      }
      success
    }
  }
`;
const mocks = [
  {
    request: {
      query: IMAGE_UPSERT,
      variables: {
        file: { path: 'juice.png' },
      },
    },
    result: {
      data: {
        imageUpload: {
          image: { id: 'image345==', alt: 'juice.png', src: 'juice.png' },
          success: true,
        },
      },
    },
  },
];

describe('Input', () => {
  it('uploads', async () => {
    const { container } = render(
      <MockedProvider mocks={mocks} addTypename={false}>
        <Input {...props} />
      </MockedProvider>
    );
    const file = new File(['(⌐□_□)'], 'juice.png', {
      type: 'image/png',
    });

    const fileEl = container.querySelector('input[type="file"]');
    Object.defineProperty(fileEl, 'files', {
      value: [file],
    });
    fireEvent.change(fileEl);
  });
});

This leads to an unmatched mutation

No more mocked responses for the query: mutation ImageUpload($file: Upload!) {
      imageUpload(file: $file) {
        image {
          id
          alt
          src
        }
        success
      }
    }
    , variables: {"file":{"path":"juice.png"}}

The variables actually passed to the client look like this

{ variables:
       { file: File { path: 'juice.png' } },

Just curious if you've already got a solution that I'm just missing.

Thanks for any input!

Variable picture got invalid value {}; Expected type Upload. Upload value invalid.

I'm using nestjs and I want to upload images but I'm getting this error message


"message": "Variable \"$picture\" got invalid value {}; Expected type Upload. Upload value invalid.",

this is how I passed my values in postman
{
operations: {"query":"mutation UploadFile($picture: Upload!) {\n uploadFile(picture: $picture)\n}"},
map: {"0": ["variables.picture"]},
0: The file I want to upload
}

and this is my code, please what I'm I doing wrong?
typegraphql

GraphQL type Upload?

Where did you get that type? type Upload is not defined anywhere
used in

 type Mutation {
    singleUpload(file: Upload!): File!
    multipleUpload(files: [Upload!]!): [File!]!
  }

Reason i'm asking: My server says path field is empty in type File when uploading from react web-app, but it works in react-native app

type Mutation {
  uploadImage(file: File): Image
}
input File {
  name: String!
  type: String!
  size: Int!
  path: String!
}
type Image {
  filename: String
  width: Int
  height: Int
}

Unable to upload multiple files

I have two mutations implemented as singleUpload & multiUpload. singleUpload working fine and unable to upload multiple files using graphQlUploadExpress. Here is my code :

server.js

const app = express();
app.use(cors());
app.use(express.json({ limit: "50mb" }));
app.use(graphqlUploadExpress({ maxFileSize: 10000000, maxFiles: 10 }));

upload.js

import GraphQLUpload from "graphql-upload/GraphQLUpload.mjs";

export default {
  Upload: GraphQLUpload,
  Mutation: {
    singleUpload: async (_, { fileInput: { id, name, file } }) => {
      try {
        const { createReadStream, filename } = await file;
        const stream = createReadStream();

        const params = {
          Bucket: process.env.S3_BUCKET,
          Key: `${id} - ${name}/${filename}`,
          Body: stream,
        };

        const res = await s3.upload(params).promise();
        console.log("File uploaded successfully");
        return `Uploaded Location: ${res.Location}`;
      } catch (error) {
        console.error("Error uploading file:", error);
        throw new Error("Failed to upload file");
      }
    },

    multiUpload: async (_, { fileInput: { id, name, files } }) => {
      try {
        const uploadPromises = files.map(async (file) => {
          const { createReadStream, filename } = await file;
          const stream = createReadStream();

          const params = {
            Bucket: process.env.S3_BUCKET,
            Key: `${id} - ${name}/${filename}`,
            Body: stream,
          };

          await s3.upload(params).promise();
          return `Uploaded: ${filename}`;
        });

        const res = await Promise.all(uploadPromises);
        console.log("File uploaded successfully");
        return `Uploaded Location: ${res.Location};`;
      } catch (error) {
        console.error("Error uploading files:", error);
        throw new Error("Failed to upload files");
      }
    },
  },

};

schema.graphql :

scalar Upload

input MultiFileInput {
  id: String!
  name: String!
  files: [Upload!]!
}

How to forward the GraphQL file without saving it first to a /upload folder

Hello, please help with this question.
I am using GraphQL for file upload and in my resolver I am forwarding it to another server. The receiving server checks the files contents and if there is already the same file it rejects the upload. This works OK most of the time but large files get broken up in 2( don't know why) and the receiving server treats the upload as 2 separate files.

Here is the resolver

async uploadFile ({files }) {                                                                                              
   const form = new FormData() 
                                                         
   return Promise.all(                                                                            
     files.map(async file => {                                                                    
       const { filename, createReadStream } = await file                                     
       const stream = createReadStream()                                                          
       let data     
                                                                                                                                            
       return new Promise((resolve, reject) => {                                                  
         stream.on('data', chunk => {                                                             
           data = chunk                                                                           
         })                                                                                                                                                                                     
         stream.on('end', () => {                                                   
           const formData = form.append('files', data, {                                          
             contentType: 'multipart/form-data',                                                  
             filename: filename                                                              
           })                                                                                     
           resolve(formData)                                                        
         })                                                                               
         stream.on('error', err => {                                                  
           reject(err)                                                                            
         })                                                                                       
       })                                                                                         
     })                                                                                           
   )                                                                                              
     .then(() => 
     // make a POST to another server                                                                                            
     )                                                                                            
     .catch(err => {                                                                              
       throw new Error(err)                                                                       
     })                                                                                           
 }

However if I first save the file to a local /upload folder as in your example and then read the file and forward it, everything is fine.
Like so

       const { filename, createReadStream } = await file                                           
       const stream = createReadStream()                                           
       //SAVE THE FILE to upload directory
       
       //READ THE FILE from the upload directory
       const filePath = `/uploads/file.csv`;           
       const stats = fs.statSync(filePath);                                             
       const fileSizeInBytes = stats.size;                                                         
       const fileStream = fs.createReadStream(filePath);                           
                                                                          
       const formData = form.append('files', fileStream, {                                           
         contentType: 'multipart/form-data',                                                   
         filename: filename,                                                                   
         knownLength: size                                                                     
       })     
                                                                                                                                        
      return  someService.postFile(                                                 
         `someEndpoint`,                        
         form,                                                                     
         { ...form.getHeaders() }                                                                                                              
       )

Ideally I am trying to forward the file without having to first save it to /uploads. Is there a way to do that?

Thank you!

Rename and more diverse examples

It's time to rethink the name and contents of this repo.

  • Apollo should be removed from the name, as uploads are not exclusive to Apollo Server and Client. A rename is also likely for apollo-upload-server: jaydenseric/graphql-upload#68. It might make sense to rename the project graphql-mutipart-request-spec-examples (or something similar but shorter, like graphql-upload-examples).
  • Apollo Server now has apollo-upload-server built in, so we need to use something else like graphql-api-koa or express-graphql to demonstrate a manual setup.

A new project structure could include a variety of cross-compatible server and client examples, centering around the GraphQL multipart request spec.

  • Server:
    • apollo-upload-server
      • With graphql-api-koa
      • With express-graphql
    • apollo-server
  • Client:
    • apollo-upload-client
    • graphql-react

It would be great to have examples for each with common cloud storage providers such as AWS S3.

How Can I use the graphql-upload with Apollo-server-lambda?

Hey Jayden,
I appreciated what you had done here with this upload example, and it is being very helpful. But I find my self stoked in how to use the graphql-upload with the apollo-server-lambda.

Can you give me any advice on how to proceed?

not issue feature file already downloaded

i suggest to add a check to see if the file was already downloaded
I passed some hour to figure out that i need to close the stream else it's not working.

here the code :

const processUpload = async (upload) => {
  const { stream, filename, mimetype, encoding } = await upload;
  const el = existInDB(filename);
  if (el.length > 0) {
    stream.resume();
    stream.on('end', () => {
      console.log('got to the end, but did not read anything');
    });
    var out = el.map(a => Object.assign({}, a))
    return out[0]
  } else {
    const { id, path } = await storeFS({ stream, filename });
    return storeDB({ id, filename, mimetype, encoding, path }); 
  }
}
export const existInDB = filename => { 
  return _.toArray(db.get("uploads")).filter(function(e) {
    return e.filename === filename;
  });
};

[BUG]: Internal Server Error Invalid Hook Calls

Steps to reproduces

  1. clone repo (git clone https://github.com/jaydenseric/apollo-upload-examples.git)
  2. cd apollo-upload-examples/app/
  3. npm install
  4. npm run dev
  5. Navigate to http://localhost:3000 in browser

Expected Behavior
Navigate to site and test

Actual Results

Internal Server Error with

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.
    at resolveDispatcher (C:\users\ondro\Desktop\apollo-upload-examples\app\.next\server\pages\_document.js:3363:13)
    at useContext (C:\users\ondro\Desktop\apollo-upload-examples\app\.next\server\pages\_document.js:3371:20)
    at Html (C:\users\ondro\Desktop\apollo-upload-examples\app\.next\server\pages\_document.js:330:29)
    at processChild (C:\Users\ondro\Desktop\apollo-upload-examples\app\node_modules\react-dom\cjs\react-dom-server.node.development.js:3043:14) 
    at resolve (C:\Users\ondro\Desktop\apollo-upload-examples\app\node_modules\react-dom\cjs\react-dom-server.node.development.js:2960:5)       
    at ReactDOMServerRenderer.render (C:\Users\ondro\Desktop\apollo-upload-examples\app\node_modules\react-dom\cjs\react-dom-server.node.development.js:3435:22)
    at ReactDOMServerRenderer.read (C:\Users\ondro\Desktop\apollo-upload-examples\app\node_modules\react-dom\cjs\react-dom-server.node.development.js:3373:29)
    at renderToStaticMarkup (C:\Users\ondro\Desktop\apollo-upload-examples\app\node_modules\react-dom\cjs\react-dom-server.node.development.js:4004:27)
    at renderDocument (C:\Users\ondro\Desktop\apollo-upload-examples\app\node_modules\next\dist\next-server\server\render.js:3:669)
    at renderToHTML (C:\Users\ondro\Desktop\apollo-upload-examples\app\node_modules\next\dist\next-server\server\render.js:52:103)

Not found error

Hello,
I am trying to reproduce the API example. I configured my .env file as NODE_ENV='development'
PORT='8080' and when I open the http://localhost:8080/ I am getting an Not found error. How can I resolve this issue?
Thanks.

Can't upload file

Hi,

I'm struggling to upload a single file

I'm using :

  • @apollo/server : v4.3.1
  • graphql-upload : v16.0.2
  • @apollo/client : v3.7.5
  • apollo-upload-client : v17.0.0

My client side :

// apollo-client.js

import { ApolloClient, ApolloLink, from, InMemoryCache } from "@apollo/client";
import { createUploadLink } from "apollo-upload-client";
import { setContext } from "@apollo/client/link/context/index.js";

const contextLink = setContext(async (_, { headers }) => {
  return {
    headers: {
      ...headers,
      "Apollo-Require-Preflight": true,
      "Content-Type": "application/json",
    },
  };
});

const errorNotAuthenticatedLink = new ApolloLink((operation, forward) => {
  return forward(operation).map((data) => {
    // if (data?.errors)
    //   if (data.errors[0]?.extensions?.code === "NotAuthenticated") {
    //     console.log(data.errors[0]?.extensions?.code);
    //     console.log(data.errors[0]?.message);
    //   }
    return data;
  });
});

const terminateLink = createUploadLink({
  uri: import.meta.env.VITE_URL_HOST,
});

const compositeLinks = from([errorNotAuthenticatedLink, terminateLink]);

const apolloClient = new ApolloClient({
  ssrMode: typeof window === "undefined",
  link: contextLink.concat(compositeLinks),
  // link: terminateLink,
  cache: new InMemoryCache(),
});

export default apolloClient;
// GraphQL Mutation

import { gql } from "@apollo/client";

export const SINGLE_UPLOAD = gql`
  mutation singleUpload($file: Upload!) {
    singleUpload(file: $file) {
      id
    }
  }
`;
// React Component, where I proceed the mutation

  const { register, handleSubmit } = useForm();

  const [singleUpload, { loading, error }] = useMutation(SINGLE_UPLOAD);

  async function handleUpload(data) {
    try {
      console.log(data.files[0]);
      const res = await singleUpload({
        variables: { file: data.files[0] },
      });
      console.log(res);
    } catch (err) {
      console.log(JSON.stringify(err));
    }
  }

  return (
    <div className={"flex w-full flex-col items-center"}>
      <form
        onSubmit={handleSubmit(handleUpload)}
        className={"flex flex-col items-center gap-10"}
      >
        <input type={"file"} {...register("files")} />
        <button type={"submit"} className={"btn-form"}>
          Upload
        </button>
        {loading && "Loading..."}
      </form>
    </div>
  );

My Server Side :

// upload.type.graphql

scalar Upload

type File {
    id: String
    name: String
    url: String
}

type Mutation {
    singleUpload(file: Upload!): File!
}
// upload.resolver.js

const { GraphQLError } = require("graphql");
const GraphQLUpload = import("graphql-upload/GraphQLUpload.mjs");
const shortId = require("shortid");

const resolveFunction = {
  Upload: GraphQLUpload,
  Mutation: {
    singleUpload: async (parent, args) => {
      console.log("Resolver: singleUpload");
      try {
        const { file } = args;
        const { createReadStream, filename } = await file;
        const storedFileName = `${shortId.generate()}-${filename}`;
        console.log(storedFileName);
        return storedFileName;
      } catch (errorUploadSingleFile) {
        console.log(
          "Something went wrong during upload file.",
          errorUploadSingleFile
        );
        return new GraphQLError(
          "Something went wrong during upload file.",
          errorUploadSingleFile,
          { extensions: { code: "ERROR-SERVER" } }
        );
      }
    },
  },
};

module.exports = resolveFunction;
// server.js 

  // Setting up the connexion with database
  await connectToDatabase();

  // Body-Parser and Cors Policies
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(
    cors({
      origin: whiteList,
      // credentials: true,
      methods: ["GET", "PUT", "POST", "OPTIONS", "PATCH", "DELETE"],
      allowedHeaders: [
        "Content-Type",
        "Authorization",
        "Apollo-Require-Preflight",
      ],
    })
  );

  // Mount TypeDefs, Resolvers and Middleware
  const schema = makeExecutableSchema({ typeDefs, resolvers });
  const schemaWithMiddleware = applyMiddleware(
    schema,
    authenticationMiddleware
  );

  // Set up Apollo Server
  const server = new ApolloServer({
    schema: schemaWithMiddleware,
    plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
    includeStacktraceInErrorResponses: process.env.NODE_ENV !== "production",
    introspection: process.env.NODE_ENV !== "production",
    // formatError: (formatError) => {
    // if (formattedError.extensions.code === "GRAPHQL_VALIDATION_FAILED")
    //   return {
    //     ...formattedError,
    //     message: "Your query doesn't match the schema. Try double-checking it !"
    //   }
    //   return {
    //     code: formatError.extensions.code,
    //     message: formatError.message
    //   };
    // }
  });

  // Lunch the Apollo Server
  await server.start();

  // Put the api endpoint
  app.use(
    "/graphql",
    expressMiddleware(server, {
      context: ({ req }) => {
        return {
          headers: req.headers,
        };
      },
    })
  );

  // Lunch Server
  try {
    await new Promise((resolve) => httpServer.listen(port, resolve));
  } catch (error) {
    console.log("Something went wrong during lunching the server.", error);
  }
  console.log(`=> Server is ready at port: ${port}`);

Here is the error I encounter, knowing that the other graphql endoints work fine :

POST http://localhost:4000/graphql 400 (Bad Request)

{
   "name":"ApolloError",
   "graphQLErrors":[
      
   ],
   "clientErrors":[
      
   ],
   "networkError":{
      "name":"ServerError",
      "response":{
         
      },
      "statusCode":400,
      "result":{
         "errors":[
            {
               "message":"POST body missing, invalid Content-Type, or JSON object has no keys.",
               "extensions":{
                  "code":"BAD_REQUEST",
                  "stacktrace":[
                     "BadRequestError: POST body missing, invalid Content-Type, or JSON object has no keys.",
                     "    at new GraphQLErrorWithCode (C:\\Users\\Baghdad\\Desktop\\MyFutur\\Blog\\backend\\node_modules\\@apollo\\server\\dist\\cjs\\internalErrorClasses.js:10:9)",
                     "    at new BadRequestError (C:\\Users\\Baghdad\\Desktop\\MyFutur\\Blog\\backend\\node_modules\\@apollo\\server\\dist\\cjs\\internalErrorClasses.js:84:9)",
                     "    at runHttpQuery (C:\\Users\\Baghdad\\Desktop\\MyFutur\\Blog\\backend\\node_modules\\@apollo\\server\\dist\\cjs\\runHttpQuery.js:81:23)",
                     "    at runPotentiallyBatchedHttpQuery (C:\\Users\\Baghdad\\Desktop\\MyFutur\\Blog\\backend\\node_modules\\@apollo\\server\\dist\\cjs\\httpBatching.js:37:57)",
                     "    at ApolloServer.executeHTTPGraphQLRequest (C:\\Users\\Baghdad\\Desktop\\MyFutur\\Blog\\backend\\node_modules\\@apollo\\server\\dist\\cjs\\ApolloServer.js:525:79)"
                  ]
               }
            }
         ]
      }
   },
   "message":"Response not successful: Received status code 400"
}

Facing Network Error Message while running locally

I have been trying to run the project locally and would want to mention helps a lot to achieve the feature.

I followed the instructions both for api and app.
Both of them show up on the browser

API Side
image

App Side

image

The following is how my logs look on the app console

{ Error: Network error: Only absolute URLs are supported
at new ApolloError (D:\Projects\apollo-upload-examples\app\node_modules\apollo-client\bundle.umd.js: 85: 32)
at D:\Projects\apollo-upload-examples\app\node_modules\apollo-client\bundle.umd.js: 1041: 45
at D:\Projects\apollo-upload-examples\app\node_modules\apollo-client\bundle.umd.js: 1413: 21
at Array.forEach ()
at D:\Projects\apollo-upload-examples\app\node_modules\apollo-client\bundle.umd.js: 1412: 22
at Map.forEach ()
at QueryManager.broadcastQueries (D:\Projects\apollo-upload-examples\app\node_modules\apollo-client\bundle.umd.js: 1407: 26)
at D:\Projects\apollo-upload-examples\app\node_modules\apollo-client\bundle.umd.js: 990: 35
at process._tickCallback (internal/process/next_tick.js: 68: 7)
graphQLErrors: [],
networkError:
TypeError: Only absolute URLs are supported
at getNodeRequestOptions (D:\Projects\apollo-upload-examples\app\node_modules\node-fetch\lib\index.js: 1293: 9)
at D:\Projects\apollo-upload-examples\app\node_modules\node-fetch\lib\index.js: 1393: 19
at new Promise ()
at Object.fetch (D:\Projects\apollo-upload-examples\app\node_modules\node-fetch\lib\index.js: 1390: 9)
at Object.fetch (D:\Projects\apollo-upload-examples\app\node_modules\cross-fetch\dist\node-ponyfill.js: 10: 20)
at D:\Projects\apollo-upload-examples\app\node_modules\apollo-upload-client\lib\index.js: 88: 7
at new Subscription (D:\Projects\apollo-upload-examples\app\node_modules\zen-observable\lib\Observable.js: 183: 34)
at Observable.subscribe (D:\Projects\apollo-upload-examples\app\node_modules\zen-observable\lib\Observable.js: 262: 14)
at D:\Projects\apollo-upload-examples\app\node_modules\apollo-link-dedup\lib\bundle.umd.js: 60: 59
at new Subscription (D:\Projects\apollo-upload-examples\app\node_modules\zen-observable\lib\Observable.js: 183: 34)
at Observable.subscribe (D:\Projects\apollo-upload-examples\app\node_modules\zen-observable\lib\Observable.js: 262: 14)
at D:\Projects\apollo-upload-examples\app\node_modules\apollo-client\bundle.umd.js: 1444: 86
at new Promise ()
at QueryManager.fetchRequest (D:\Projects\apollo-upload-examples\app\node_modules\apollo-client\bundle.umd.js: 1442: 20)
at QueryManager.fetchQuery (D:\Projects\apollo-upload-examples\app\node_modules\apollo-client\bundle.umd.js: 975: 42)
at QueryManager.startQuery (D:\Projects\apollo-upload-examples\app\node_modules\apollo-client\bundle.umd.js: 1300: 18),
message: 'Network error: Only absolute URLs are supported',
extraInfo: undefined
}

api side console looks like this

λ npm run dev

apollo-upload-examples-api@ dev D:\Projects\apollo-upload-examples\api
nodemon -i db.json

[nodemon] 1.18.9
[nodemon] to restart at any time, enter rs
[nodemon] watching: .
[nodemon] starting node --experimental-modules -r dotenv/config server
(node:11800) ExperimentalWarning: The ESM module loader is experimental.
Serving http://localhost:3001 for development.

Is there something I am completely missing on the setup side?

And when I try uploading a Blob file it shows up like this on the browser console

image

File not being passed to server

I'm hoping you can help me see what I am doing wrong here.

On the client the file is being passed to the mutation:
image

But then on the server file is undefined:
image

I think something is wrong with my client side mutation (not sure that's the right way to say that). Please let me know if more information is needed.

blocked as a potential Cross-Site Request Forgery (CSRF)

How to fix this :

"This operation has been blocked as a potential Cross-Site Request Forgery (CSRF). Please either specify a 'content-type' header (with a type that is not one of application/x-www-form-urlencoded, multipart/form-data, text/plain) or provide a non-empty value for one of the following headers: x-apollo-operation-name, apollo-require-preflight\n"

Unhandled Rejection (Error): Unexpected token M in JSON at position 0

I'm getting this error Unhandled Rejection (Error): Unexpected token M in JSON at position 0
any idea why? below is my code and screenshots of the error in console.
app.js
const client = new ApolloClient({ cache: new InMemoryCache(), link: createUploadLink({ uri: "https://onegraph.azurewebsites.net/api/magda", }), });
input component change event
const onChange = (e) => { let f = e.target.files[0]; let v = { variables: { file: f } }; uploadFile(v).then(() => { apolloClient.resetStore(); }); };
upload file query
`import gql from "graphql-tag";

export const UPLOADFILE = gqlmutation uploadFile($file: Upload!) { uploadFile(file: $file) { name type size lastModified } };`
Screen Shot 2020-09-04 at 9 19 26 AM
Screen Shot 2020-09-04 at 9 21 26 AM
Screen Shot 2020-09-04 at 9 21 02 AM
Screen Shot 2020-09-04 at 9 20 10 AM

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.