duanjian5059 2018-10-05 08:51
浏览 81

无法从Node Js向PHP传递值到php

I have a php file on server which have a function, and I have Node Js API also. I want to pass Node Js value to php script then get back the function output to node js.

I tried this using cookie-parser as sugggested by Christian in here. But it does not work

php script

$max = $_COOKIE["usrMob"];  // Taken from cookie
$min = 1111;

$number = mt_rand($min, $max);  // Find random number
echo $number;   // Send back to Node Js


const express = require("express");
const cookieParser = require('cookie-parser'); 

const app = express();
app.use(cookieParser('Your Secret'));

router.get('/cookie', function (req,res)
    // Set cookie
    res.cookie('userMax', '46556') // options is optional
    console.log("Cookie is : " + res.cookie);
  • 写回答

1条回答 默认 最新

  • douguanci9158 2018-10-05 09:45

    I have a php file on server which have a function, and I have Node Js API also. I want to pass Node Js value to php script then get back the function output to node js.

    I tried this using cookie-parser as sugggested by Christian in here. But it does not work

    Short answer

    Sharing COOKIES won't work because of CORS, your nodejs server must be in the allow origin list of the PHP server.

    Long answer

    COOKIES are very used when storing user settings/tokens/password or some sensitive data on your browser that allows the user browsing experience behave different mostly the user decisions.

    Therefore they cannot be sent in requests when different servers communicates between them unless they are allowed to leave to an 'authorized-origin' otherwise that would be a major leak of data through cookies, say hello to CORS (unless you don't own the target server).


    You have a script on a TargetServer(TS), that sets a cookie there when user does some stuff. After the user finishes with your script you want to send data back to YourServer(YS), when the AJAX triggers, cookies won't be sent with the request as you normally see when you develop on localhost. Following your stack of tools, another problem issues, each request that you'll make to YS will generate a new id/session (i'm looking at you PHPSESSID), and that means, you won't know for example if the user is logged or not, and you know for sure that he already logged earlier (Yes - he is logged, but in another session file ... ).


    1. Find an appropriate mechanism for encrypt/decrypt strings that your script and php will know.
    2. When you're sending a request from TS to YS add a custom header that YS will expect.eg. REQUEST-CUSTOM-HEADER: encodedVersionOf('hey-give-me-the-session-id') , PHP will see the incoming header, will decodeVersionOf('hey-give-me-the-session-id') and will trigger some special if and send you a response with a different header RESPONSE-CUSTOM-HEADER: encodedVersionOf('here-is-the-session-id'). Your script will now save it in COOKIES so you won't have to request it again. and just append it to your header on future requests.
    3. If PHP recognizes the incoming string as a valid session then php can load that session that you know you had data in it with session_id($incoming_id), make sure to set session_id before session_start
    4. I highly advise using JWT for this kind of things or some encrypted stringify json, so you can have an object like {session_id : 12idn3oind, userInfo: {name: 'test'}}.
    5. Exchanging data through headers is the next best thing when CORS is involved.

    I tackled this example once, wasn't pretty to do, but worth it in the end.

    You can send/receive data to/from php, only thing is that you should use headers so you won't affect php output. Since you own both servers you can do something like:


    1. npm install -S express
    2. Make sure you have enabled headers_module/mod_headers on your webserver.
    3. We will use custom headers so you should allow & expose them:


    Header add Access-Control-Allow-Headers "node-request, node-response"
    Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
    Header add Access-Control-Expose-Headers "node-request, node-response"
    Header add Access-Control-Allow-Origin "*"


        $max = @$_COOKIE["usrMob"];  // Taken from cookie
        $min = 1111;
        $number = rand($min, $max);  // Find random number
        echo $number;   // Send back to Node Js
        if( isset($_SERVER['HTTP_NODE_REQUEST'])){
           $req = json_decode($_SERVER['HTTP_NODE_REQUEST'], true);
           $data = array();
           // 'givemeanumber' is sent from Node.js server
           if( isset($req['givemeanumber']) ){
             $data = array(
                 'number' => $number
           header('NODE-RESPONSE: '. json_encode(array("req" => $req, "res"=> $data)));


    Don't forget to change these line to point to your php-server:

    getFromPHP('localhost', '9999', '/path-to-php-script', {givemeanumber: 1})


    const express = require("express");
    const app = express();
    const port = 9999;
    const { getFromPHP } = require('./middleware.js');
    const apachePHPconfig = {
        host: 'localhost',
        port: 80,
        urlpath: 'path-to-php-script'
        getFromPHP(apachePHPconfig.host, apachePHPconfig.port, apachePHPconfig.urlpath , {givemeanumber: 1}),
        function (req, res) {
            // here is your php object
            console.log('php', req.php);
    app.listen(port, () => {
        console.log(`Example app listening on port ${port}!`)


     *  Middleware to get data from PHP
    const getFromPHP = (phpHost, phpPort, phpPath, phpObject) => {
        if (typeof phpHost === 'undefined') {
            throw new Error('phpHost was not defined');
        if (typeof phpPort === 'undefined') {
            throw new Error('phpPort was not defined');
        if (typeof phpPath === 'undefined') {
            phpPath = '/';
        if (typeof phpObject !== 'object' ) {
            phpObject = {};
        return (req, res, next) => {
            if (typeof req.php === 'undefined') {
                req.php = {};
            const options = {
                hostname: phpHost, // change this to your php server host
                port: phpPort, // change this with your php server port
                path: phpPath, // change this with your php server path to script
                method: 'POST',
                headers: {
                    // here we send 'NODE-REQUEST', it will be available in php unde $_SERVER global prefixed with HTTP_ string because is a custom client request header.
                    'NODE-REQUEST': JSON.stringify(phpObject)
            const isJSON = (str ) => {
                try {
                    let j = JSON.parse(str);
                    return typeof j === 'object' && j !== null;
                } catch (e) {
                    return false;
            const httpModule = require('http');
            let reqHttp = httpModule.request(options, (response) => {
                if( typeof response.headers['node-response'] === 'undefined' || !isJSON(response.headers['node-response'])){
                    req.php = {};
                    req.php =  JSON.parse(response.headers['node-response']);
                // START - Remove this code when everything runs as expected
                let dataStack = []; 
                response.on('data', (data)=>{ 
                response.on('end', ()=>{ 
                   console.log("PHP HEADERS", response.headers) 
                   console.log('PHP OUTPUT', dataStack.join('')); 
                // END
            reqHttp.on('error', (e) => {
                console.error(`problem with request to php server: ${e.message}`);
            reqHttp.on('end', () => {
    exports.getFromPHP = getFromPHP;
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥60 AS自带模拟器AVD Root 和 Xposed安装
  • ¥15 Esp32的microPython设备中main.py文件无法开机自启动
  • ¥30 哪位搞Android的编程师可以帮我远程一下,悬赏30元
  • ¥15 solidity部署上合约,可以mint,也继承接口了,在区块链也不显示代币名字
  • ¥15 讨论 博士论文交互项怎么讨论?
  • ¥50 在集成BiLSTM和GCN模型时遇到了问题
  • ¥33 集成BiLSTM模型和GCN模型时,前模型的输出不匹配后模型的输入
  • ¥15 关于液体厚度提取,和铺展轨迹数据化处理
  • ¥20 对方微信是wxid如何添加成好友?或者转换成微信号?
  • ¥15 求这个内容该怎么做一个程序,写什么样的代码