-1

I'm trying to get only "Test" response from a PHP file with ReactJS and Axios. But get whole code from rest.php instead of "Test".

When i try to access localhost/rest.php only get "Test" word and PHP is working good.

What i'm doing wrong?

Thanks

app.jsx


import React, { Component } from 'react';

import './App.css';

import axios from 'axios';


class App extends Component {
  constructor(props) {
    super(props);
    this.state = {

    };
  }


  componentDidMount() {
    const url = './api/rest.php'

        axios.get(url)
      .then(res => {
        const persons = res.data;
        this.setState({ contacts: persons });
      })


  }


  render() {
    return (
      <div style={{ width: "100%", height: "100vh" }}>
          {this.state.contacts}
      </div>
    )
  }
}

export default App;

and rest.php

    header("Access-Control-Allow-Origin: *");

        $data = json_decode(file_get_contents("php://input"), true);

    $host = "localhost"; 
    $user = "root"; 
    $password = ""; 
    $dbname = "musteri"; 
    //$con = mysqli_connect($host, $user, $password,$dbname);


    echo "test";
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Metin Genç
  • 99
  • 2
  • 13
  • That's unrelated to MySQL, React and Axios. For some reason, your local webserver treats your Php file as text. – Emile Bergeron Sep 10 '19 at 15:17
  • Possible duplicate of [Apache shows php code instead of executing](https://stackoverflow.com/questions/12142172/apache-shows-php-code-instead-of-executing) and [PHP code is not being executed, instead code shows on the page](https://stackoverflow.com/questions/5121495/php-code-is-not-being-executed-instead-code-shows-on-the-page?rq=1) – esqew Sep 10 '19 at 15:19
  • but if is an apache problem it should be render the php file as text as well when he visit the page right? – Nico Sep 10 '19 at 15:21
  • this is not apache problem because PHP file return "Test" when i call direct from browser – Metin Genç Sep 10 '19 at 15:26
  • Then the problem is that the URL `./api/rest.php` resolves to somewhere different to `localhost/rest.php` (and so it is likely an Apache problem in so much as you are bypassing Apache entirely and shouldn't) – Quentin Sep 10 '19 at 15:50

1 Answers1

4

axios.get(url) actually read the PHP local file, not the result of the PHP script.

If you want the interpreted version you'll have to set url = 'http://the-server/api/rest.php' (replace 'the-server' by your Apache server, maybe 'localhost')

  • yes, with localhost it worked. But at this time get html tags as plain text, `echo "test"."
    "."test2"`. i seeing `
    ` as plain text, not a new line
    – Metin Genç Sep 11 '19 at 06:18
  • Because the string `
    ` is an HTML code for newline. If you want a real new line (CR) use the PHP_EOL constant : `echo "test".PHP_EOL."test2";`
    – Thierry Leroux Sep 11 '19 at 13:50