没有来自php和Axios Node Js的响应输出

I want to send value from Node Express to php in server. The php script has a calculation then php should return the result back to Node Express.

But php script does not return any values. The following console echos Undefined

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

console output of Node Js

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
Accept: application/json, text/plain, */*
Content-Type: application/json;charset=utf-8
User-Agent: axios/0.18.0
Content-Length: 2
Host: mytestpage.com
Connection: close

',
     _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 script

<?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();

    }    
?>

Node script

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));
})
dqgo99177
dqgo99177 我认为PHP脚本中的问题。我没有回复为有效的JSON。我应该在PHP脚本中的任何数组或任何内容之前声明吗?
大约 2 年之前 回复
duangang2825
duangang2825 邮递员仍然没有停止加载。节点打印UnhandledPromiseRejectionWarning:TypeError:将循环结构转换为JSON
大约 2 年之前 回复
drl971115
drl971115 好。让我们从头开始。在邮递员中,当你使用邮递员向index.php发帖请求(并使用formData或x-www-form-urlencoded将takeFromNodeparam添加到请求主体并使用某个值)时,按“发送”,你应该得到一些回复在邮递员的回应“身体”(仍在邮递员)。你得到了什么?邮递员中没有“网络标签”。这样做将测试PHP文件而不调用任何节点或任何东西。如果仍然不起作用,那么你要么完全不像我刚才提到的那样,要么你的代码看起来不像你说的那样。
大约 2 年之前 回复
douyimiao1993
douyimiao1993 我使用vartakeFromNode=req.body.takeFromNode给takeFromNode的值;
大约 2 年之前 回复
doutangshuan6473
doutangshuan6473 正如你所说,我改为$_POST。然后浏览器仅支持GET请求。使用浏览器没有POST请求。无论如何,我使用邮递员给予价值并检查网络选项卡,它显示状态200。
大约 2 年之前 回复
duanpan3166
duanpan3166 另外,在尝试在对php文件的请求中使用它之前,在JS中设置值takeFromNode在哪里?
大约 2 年之前 回复
dtv7174
dtv7174 你是什​​么意思“因为POST请求”?这也可以在网络标签中查看。如果您将$POST更改为$_POST,请将表单paramtakeFromNode设置为postman的某个值,发布到http://mytestpage.com/calculate/index.php响应是什么?
大约 2 年之前 回复
doufuxi7093
doufuxi7093 我使用Postman检查这个,因为POST请求。
大约 2 年之前 回复
doubei8168
doubei8168 检查浏览器开发工具中的网络选项卡,查看实际请求的内容,发布的数据以及返回的内容。关于PHP,就我所见,上述类型是唯一的问题。
大约 2 年之前 回复
dsyk33753
dsyk33753 没有成功也没有定义
大约 2 年之前 回复
donglanche9257
donglanche9257 它应该是$_POST,而不是$POST。
大约 2 年之前 回复

1个回答



Simon 说,Axios使用 JSON </ p> \ n

更改以下</ p>

  axios.post('http://mytestpage.com/calculate/index.php', {takeFromNode:takeFromNode})\  n </ code> </ pre> 

</ p>

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

可以正常工作。</ p>
</ div>

展开原文

原文

As Simon said, Axios using JSON

Change the following

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

to

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

will work fine.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐