首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Strapi中更新产品的自定义API返回405

在Strapi中更新产品的自定义API返回405
EN

Stack Overflow用户
提问于 2022-06-24 10:46:15
回答 1查看 232关注 0票数 0

我目前正在设置Strapi V4,以便在收到来自PIM的另一个请求后用PUT请求更新产品集合。

我刚刚生成了一个使用strapi生成CLI的自定义API,并且基本上设置了两个函数在我的控制器内完成上述任务,用于更新产品路由。

代码语言:javascript
运行
复制
"use strict";

var axios = require("axios");
var qs = require("qs");

function getUpdates() {
  var baseLinkerData = qs.stringify({
    method: "getInventoryProductsList",
    parameters: '{"inventory_id": 3807}',
  });
  var config = {
    method: "post",
    url: "https://api.baselinker.com/connector.php",
    headers: {
      "X-BLToken": `${process.env.BL_TOKEN}`,
      "Content-Type": "application/x-www-form-urlencoded",
    },
    data: baseLinkerData,
  };

  axios(config)
    .then(function (response) {
      // const updates = JSON.stringify(response.data.products);
      const updates = response.data.products;
      // console.log(updates);
      updateProducts(updates);
    })
    .catch(function (error) {
      console.log(error);
    });
}

function updateProducts(productList) {
  // Prepare a request

  for (const [key, value] of Object.entries(productList)) {

    // Mapping of the product data
    var data = JSON.stringify({
      data: {
        id: value.id,
        ean: value.ean ? value.ean : null,
        sku: value.sku ? value.sku : null,
        name: value.name,
        quantity: value.stock ? parseInt(value.stock.bl_5076) : 0,
        price_brutto: value.prices ? parseFloat(value.prices["3624"]) : 0,
      },
    });
    console.log(data);

   // Config for the request
    var config = {
      method: "put",
      url: `${process.env.MY_HEROKU_URL}/api/products/${key}`,
      headers: {
        Authorization: process.env.STRAPI_API_AUTH,
        "Content-Type": "application/json",
      },
      data: data,
    };

    // Send the request

    axios(config)
      .then(function (response) {
        console.log(JSON.stringify(response.data));
      })
      .catch(function (error) {
        console.log(error);
      });
    // });
  }
}
/**
 * A set of functions called "actions" for `update-products`
 */

module.exports = {
  exampleAction: async (ctx, next) => {
    try {
      getUpdates();
      ctx.body = "ok";
    } catch (err) {
      ctx.body = err;
    }
  },
};

,在下面的代码中我得到了405错误:

代码语言:javascript
运行
复制
Error: connect EMFILE 00.000.00.000:443 - Local (undefined:undefined)
    at internalConnect (net.js:934:16)
    at defaultTriggerAsyncIdScope (internal/async_hooks.js:452:18)
    at GetAddrInfoReqWrap.emitLookup [as callback] (net.js:1077:9)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:73:8) {
  errno: -24,
  code: 'EMFILE',
  syscall: 'connect',
  address: '00.000.00.000',
  port: 443,
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [Function: httpAdapter],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    validateStatus: [Function: validateStatus],
    headers: {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/json',
      Authorization: 'process.env.BEARER',
      'User-Agent': 'axios/0.24.0',
      'Content-Length': 82
    },
    method: 'put',
    url: 'https://sampleurl.herokuapp.com/api/products/16611',
    data: '{"data":{"id":21847637,"ean":null,"sku":null,"name":"GRA O TRON Winter is here – Kubek termiczny","quantity":1,"price_brutto":55.99}}'
    },
  request: <ref *1> Writable {
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: true,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,
      buffered: [],
      bufferedIndex: 0,
      allBuffers: true,
      allNoop: true,
      pendingcb: 0,
      prefinished: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: true,
      errored: null,
      closed: false
    },
    _events: [Object: null prototype] {
      response: [Function: handleResponse],
      error: [Function: handleRequestError]
    },
    _eventsCount: 2,
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: 10485760,
      protocol: 'https:',
      path: '/api/products/16611',
      method: 'PUT',
      headers: [Object],
      agent: undefined,
      agents: [Object],
      auth: undefined,
      hostname: 'sampleurl.herokuapp.com',
      port: null,
      nativeProtocols: [Object],
      pathname: '/api/products/16611'
    },
    _ended: false,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 82,
    _requestBodyBuffers: [ [Object] ],
    _onNativeResponse: [Function (anonymous)],
    _currentRequest: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: true,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: null,
      _hasBody: true,
      _trailer: '',
      finished: false,
      _headerSent: true,
      socket: [TLSSocket],
      _header: 'PUT /api/products/16611 HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Content-Type: application/json\r\n' +
        'Author^Cse,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'sampleurl.herokuapp.com',
      protocol: 'https:',
      _redirectable: [Circular *1],
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    _currentUrl: 'https://sampleurl.herokuapp.com/api/products/16611',
    [Symbol(kCapture)]: false
  },
  response: undefined,
  isAxiosError: true,
  toJSON: [Function: toJSON]
}

我不知道这是怎么回事,我还在想,当第一个请求已经被提取的时候,不使用API更新集合的另一种方式是什么呢?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-24 21:27:29

我通过使用这两个调用来做到这一点--取决于我的控制哈希值和产品是否存在。

代码语言:javascript
运行
复制
await strapi.db.query('api::product.product').update(query)
await strapi.db.query('api::product.product').create(query)

对update和create的查询是相同的,但是create查询没有“where”参数。

代码语言:javascript
运行
复制
const query = {
  where: {
    id: existing_products[new_data.import_code].id
  },
  data: {
    ...new_data,
    import_date_time: new Date().toISOString(),
    import_hash: hash
  }
}

另外,注意哈希值--我从“new_data”中计算它,并且只有当它们不同时才导入它,所以如果没有任何变化,我就不必更新记录。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72742900

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档