php和Axios Node Js没有响应输出

时间:2018-10-12 05:01:42

标签: php node.js express

我想从Node Express向服务器中的php发送值。 php脚本进行了计算,然后php应该将结果返回给Node Express。

但是php脚本不返回任何值。以下控制台回显Undefined

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

节点J的控制台输出

Connected successfully to the database
{ 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')

route.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));
})

1 个答案:

答案 0 :(得分:0)

正如Simon所说,Axios使用JSON

更改以下内容

  axios.post('http://mytestpage.com/calculate/index.php', {takeFromNode: takeFromNode})

  axios.post('http://mytestpage.com/calculate/index.php',require('querystring').stringify({takeFromNode: takeFromNode}))

可以正常工作。