【问题标题】:php or Node js does not support for Axiosphp 或 Node js 不支持 Axios
【发布时间】:2019-03-19 10:23:11
【问题描述】:

值应该从节点 js 发送到 php 脚本。 php 脚本包含节点 js 发送值时的逻辑。之后 php 将计算的值返回给 Node js。问题是当值从节点发送时,节点 js 中没有输出(返回)。这个 php 正确吗?

console.log(response.data.Final);  // Undefined
console.log(response.Final);        // Undefined
console.log(response.data.result);  // Undefined

console.log(响应)

{ status: 200,
  statusText: 'OK',
  headers:
   { date: 'Wed, 10 Oct 2018 14:28:19 GMT',
     server: 'Apache',
     'x-powered-by': 'PHP/7.2.10',
     'access-control-allow-headers': 'node-request, node-response, node-request, node-response',
     'access-control-allow-methods': 'PUT, GET, POST, DELETE, OPTIONS, PUT, GET, POST, DELETE, OPTIONS',
     'access-control-expose-headers': 'node-request, node-response, node-request, node-response',
     'access-control-allow-origin': '*, *',
     'content-length': '0',
     connection: 'close',
     'content-type': 'text/html; charset=UTF-8' },
  config:
   { adapter: [Function: httpAdapter],
     transformRequest: { '0': [Function: transformRequest] },
     transformResponse: { '0': [Function: transformResponse] },
     timeout: 0,
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     headers:
      { Accept: 'application/json, text/plain, */*',
        'Content-Type': 'application/json;charset=utf-8',
        'User-Agent': 'axios/0.18.0',
        'Content-Length': 2 },
     method: 'post',
     url: 'http://mytestpage.com/calculate/index.php',
     data: '{}' },
  request:
   ClientRequest {
     domain: null,
     _events:
      { socket: [Function],
        abort: [Function],
        aborted: [Function],
        error: [Function],
        timeout: [Function],
        prefinish: [Function: requestOnPrefinish] },
     _eventsCount: 6,
     _maxListeners: undefined,
     output: [],
     outputEncodings: [],
     outputCallbacks: [],
     outputSize: 0,
     writable: true,
     _last: true,
     upgrading: false,
     chunkedEncoding: false,
     shouldKeepAlive: false,
     useChunkedEncodingByDefault: true,
     sendDate: false,
     _removedConnection: false,
     _removedContLen: false,
     _removedTE: false,
     _contentLength: null,
     _hasBody: true,
     _trailer: '',
     finished: true,
     _headerSent: true,
     socket:
      Socket {
        connecting: false,
        _hadError: false,
        _handle: null,
        _parent: null,
        _host: 'mytestpage.com',
        _readableState: [Object],
        readable: false,
        domain: null,
        _events: [Object],
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: false,
        allowHalfOpen: false,
        _bytesDispatched: 221,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: null,
        _server: null,
        parser: null,
        _httpMessage: [Circular],
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1,
        [Symbol(asyncId)]: 132,
        [Symbol(bytesRead)]: 604 },
     connection:
      Socket {
        connecting: false,
        _hadError: false,
        _handle: null,
        _parent: null,
        _host: 'mytestpage.com',
        _readableState: [Object],
        readable: false,
        domain: null,
        _events: [Object],
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: false,
        allowHalfOpen: false,
        _bytesDispatched: 221,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: null,
        _server: null,
        parser: null,
        _httpMessage: [Circular],
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1,
        [Symbol(asyncId)]: 132,
        [Symbol(bytesRead)]: 604 },
     _header: 'POST /calculate/index.php HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nContent-Type: application/json;charset=utf-8\r\nUser-Agent: axios/0.18.0\r\nContent-Length: 2\r\nHost: mytestpage.com\r\nConnection: close\r\n\r\n',
     _onPendingData: [Function: noopPendingOutput],
     agent:
      Agent {
        domain: null,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        defaultPort: 80,
        protocol: 'http:',
        options: [Object],
        requests: {},
        sockets: [Object],
        freeSockets: {},
        keepAliveMsecs: 1000,
        keepAlive: false,
        maxSockets: Infinity,
        maxFreeSockets: 256 },
     socketPath: undefined,
     timeout: undefined,
     method: 'POST',
     path: '/calculate/index.php',
     _ended: true,
     res:
      IncomingMessage {
        _readableState: [Object],
        readable: false,
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        socket: [Object],
        connection: [Object],
        httpVersionMajor: 1,
        httpVersionMinor: 1,
        httpVersion: '1.1',
        complete: true,
        headers: [Object],
        rawHeaders: [Array],
        trailers: {},
        rawTrailers: [],
        upgrade: false,
        url: '',
        method: null,
        statusCode: 200,
        statusMessage: 'OK',
        client: [Object],
        _consuming: true,
        _dumped: false,
        req: [Circular],
        responseUrl: 'http://mytestpage.com/calculate/index.php',
        redirects: [],
        read: [Function] },
     aborted: undefined,
     timeoutCb: null,
     upgradeOrConnect: false,
     parser: null,
     maxHeadersCount: null,
     _redirectable:
      Writable {
        _writableState: [Object],
        writable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _options: [Object],
        _redirectCount: 0,
        _redirects: [],
        _requestBodyLength: 2,
        _requestBodyBuffers: [],
        _onNativeResponse: [Function],
        _currentRequest: [Circular],
        _currentUrl: 'http://mytestpage.com/calculate/index.php' },
     [Symbol(outHeadersKey)]:
      { accept: [Array],
        'content-type': [Array],
        'user-agent': [Array],
        'content-length': [Array],
        host: [Array] } },
  data: '' }

php 脚本

<?php
    if(isset($_POST['takeFromNode']))
    {

    $num1 = 10;
    $num2 = $_POST['takeFromNode'];          // getting from Node Js

    $result = ($num1 + $num2);     // This result should be return

    print(json_encode(['Final' => $result]));  // Code to return back
    exit();

    }    
?>

节点脚本

var axios = require('axios')
router.post("/calculate", function (req, res, next)
{
  axios.post('http://mytestpage.com/calculate/index.php', {takeFromNode: takeFromNode})
  .then(response => {
    if(response)
    {
      console.log(response);
    }
  })
  .catch(error => res.status(500).send(error));
})

【问题讨论】:

    标签: javascript php node.js axios


    【解决方案1】:

    Axios 默认将帖子正文编码为 JSON,即Content-Type: application/json。 PHP $_POST[...] 期望它是 application/x-www-form-urlencoded

    不要将对象传递给axios.post 的第二个参数,而是传递一个urlencoded 字符串:

    require('querystring').stringify({takeFromNode: takeFromNode})

    【讨论】:

    • 感谢您的努力和建议,效果很好。
    猜你喜欢
    • 2015-04-15
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 2022-09-25
    • 2012-10-18
    • 1970-01-01
    相关资源
    最近更新 更多