简体   繁体   English

GraphQL 文件上传纯 JS “必须提供查询字符串。”

[英]GraphQL file upload plain JS "Must provide query string."

I am uploading files to GraphQL API with plain JS.我正在使用普通 JS 将文件上传到 GraphQL API。 I've been doing this from the same origin for months now and now am trying to implement the exact same thing externally with NodeJS.几个月来我一直在同一个来源做这件事,现在正试图用 NodeJS 在外部实现完全相同的东西。

My code looks something like this:我的代码看起来像这样:

const FormData = require('form-data');
const fs = require('fs')
const axios = require('axios')

const payload = generateRequest(input)

axios.post(apiBaseUrl + "/graphql", payload, {
      headers: {...payload.getHeaders()}
    }).then(response => {
        let res = response.data
        if (res.data.triggerPcWorkflow.status === 200) {
            console.log("success!")
        } else {
            console.error(res.data.triggerPcWorkflow.message)
        }
      })
      .catch(err => {
          if (err.response) {
              console.log(err.response.data);
              console.log(err.response.status);
              console.log(err.response.headers);
          }
      })

With the generateRequest function generating the multipart payload ( https://github.com/jaydenseric/graphql-multipart-request-spec ).使用generateRequest function 生成多部分有效负载( https://github.com/jaydenseric/graphql-multipart-request-spec )。

I have two identical versions of the Backend running on localhost:5000 and mycooldomain.com .我在localhost:5000mycooldomain.com上运行了两个相同版本的后端。 When setting apiBaseUrl to http://localhost:5000 everything works flawlessly.apiBaseUrl设置为http://localhost:5000时,一切正常。 However just by changing the URL to https://www.mycooldmain.com I get a 400 error thrown at me with { errors: [ { message: 'Must provide query string.' } ] }但是,只需将 URL 更改为https://www.mycooldmain.com我收到 400 错误, { errors: [ { message: 'Must provide query string.' } ] } { errors: [ { message: 'Must provide query string.' } ] }

BTW: A simple query works with both URLs...顺便说一句:一个简单的query适用于两个 URL...

Here is my generateRequest function:这是我的generateRequest function:

const mutation = `
mutation MyMutation($xyz: String) {
    doSomething(myInput: $xyz) {
        status 
        message
    }
}
`

let sendData = new FormData();
const fileNull = [];
    
// map
files = generateRequestInput.files
let map = '{'

for (let i = 0; i < files.length; i++) {
  fileNull.push(null);
  map += `"${i}": ["variables.files.${i}"], `
}

map = map.substring(0, map.length-2);
map += '}'

// operations
const operations = JSON.stringify({
    query: mutation,
    variables: {
        "xyz": "Hello"
    }
  });

// build payload
sendData.append("operations", operations)
sendData.append("map", map)
for (let i = 0; i < files.length; i++) {
    sendData.append(i, files[i]);
}

return sendData

I know that map looks a bit ugly but thats not the point (unless it is).我知道map看起来有点丑,但这不是重点(除非是)。

Has anyone had a similar problem or knows what my error is here?有没有人遇到过类似的问题或知道我的错误是什么? Thanks!谢谢!

I skipped on the axios dependency and implemented the request with FormData directly.我跳过了axios依赖项并直接使用FormData实现了请求。

The code below works.下面的代码有效。

function makeRequest(formData, options) {
  formData.submit(options, (err, res) => {
    if (err) {
      console.error(err.message)
      return
    } else {
      
      if (res.statusCode < 200 || res.statusCode > 299) {
        console.error(`HTTP status code ${res.statusCode}`)
      }
      
      const body = []
      res.on('data', (chunk) => body.push(chunk))
      res.on('end', () => {
        const resString = Buffer.concat(body).toString()
        console.log(resString)
      })
    }
  })
}

const options = {
  host: 'mycooldomain.com',
  port: 443,
  path: '/graphql',
  method: 'POST',
  protocol: 'https:'
}

makeRequest(payload, options)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么会出现错误“必须提供查询字符串”。express-graphql? - Why I'm getting the error “Must provide query string.” express-graphql? Apollo Server,Graphql-必须提供查询字符串 - Apollo Server, Graphql - Must provide query string GraphQL:错误:必须提供文档 - GraphQL: Error: Must provide Document 使用纯AJAX / JS和Django上传文件 - Upload file with plain AJAX/JS and Django 将graphql查询.gql文件导入纯Javascript并运行axios调用 - Import graphql query .gql file into plain Javascript and run an axios call 错误:正文必须是字符串。 收到:{ resolvers: [[function HelloResolver]], validate: false } 使用 Type-graphql 和 apollo-server-express 时 - Error: Body must be a string. Received: { resolvers: [[function HelloResolver]], validate: false } when using Type-graphql and apollo-server-express 运行gulp会导致“ path.js:7抛出新的TypeError(&#39;路径必须是字符串。已接收&#39;+ inspect(path));” - Running gulp gives “path.js:7 throw new TypeError('Path must be a string. Received ' + inspect(path));” 自定义Gulp.js插件:TypeError“路径必须是一个字符串。 收到undefined“ - Custom Gulp.js plugin: TypeError “Path must be a string. Received undefined” Lstat:类型错误:路径必须是字符串。 - Lstat: Type error: path must be a string. Mongo过滤器转换为GraphQL查询| 必须是一个对象,得到_String_ - Mongo filter into GraphQL query | must be an object, got _String_
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM