简体   繁体   中英

PHP session not working in Aurelia

I'm using Aurelia with PHP as backend. Here is my view with its model:

home.html

<template>
    <require from="datepicker.js"></require>
    <form submit.delegate="submit()">
        <input value.bind="name"></input>
        <input value.bind="age"></input>
        <button type="submit" name="submit">Submit
        </button>
    </form>
</template>

home.js

import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import 'fetch';

@inject(HttpClient)
export class Home {
  name;
  age;

  constructor(http) {
    this.http = http;
  }

  submit() {
    this.jsonobj = {
      'name': this.name,
      'age': this.age
    };

    if (this.jsonobj.name && this.jsonobj.age) {
      this.http.fetch('dist/components/ses.php', {
        method: 'post',
        body: JSON.stringify(this.jsonobj)
      })
        .then(response =>  response.json())
          .then(data => 
          { 
            console.log(data);
          });
    }
  }
}

And here is the PHP script:

ses.php

<?php
    session_start();

    $word = 'lol';
    if(!isset($_SESSION['username'])){
        $_SESSION['username'] = 'kil';
    }

    $input = file_get_contents('php://input');
    $input_json_array = json_decode($input);

    echo json_encode(array('item' => $_SESSION['username']));

?>

I expect that after the first call to the script, $_SESSION['username'] will be set to 'kil'. So on next ajax post !isset($_SESSION['username'] wont evaluate to true but it does which means PHP session isn't working.

By default fetch (the web standard that aurelia-fetch-client is built on) does not send cookies. You'll need to use credentials: 'include' in your request init object.

Two great resources for fetch:

The codez:

this.http.fetch('dist/components/ses.php', {
    credentials: 'include', // <-------------------------------------
    method: 'post',
    body: JSON.stringify(this.jsonobj)
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM