3

I am new in React.I am looking for how to save the data of a form with axios in a database. But not working..

My API.JS

const axios = require ("axios");
const querystring = require('querystring');

export function getPeople(){
  return axios.get(`http://127.0.0.1:9000/people`)
}

export function postPeople(){
  axios.post('http://127.0.0.1:9000/people', querystring.stringify({
    'bar': 123
  }));
}

My app.js:

import React, { Component } from 'react';
import { getPeople, postPeople } from './api';

addItem = () => {
    postPeople();
}

My Express.js:

var express = require('express')
var cors = require('cors')
var app = express()


app.get('/people', cors(), function (req, res, next) {
  res.json([
    {
      id: 0,
      name: "0",
      age: 20,
      city: 'R0eiro',
      country: '04'
    },
    {
      id: 1,
      name: "0",
      age: 29,
      city: 'Minas 00',
      country: '00'
    },
})

app.listen(9000, function () {
  console.log('The server is running in the port 9000')
})

Be givin that errors:

POST http://127.0.0.1:9000/people 404 (Not Found)

Failed to load http://127.0.0.1:9000/people: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404.

Uncaught (in promise) Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:87)

Someone help me?

Jota
  • 819
  • 6
  • 24
  • 41

2 Answers2

2

You're running into a CORS problem.

Taken from this SO answer:

Access-Control-Allow-Origin is a CORS (Cross-Origin Resource Sharing) header.

When Site A tries to fetch content from Site B, Site B can send an Access-Control-Allow-Origin response header to tell the browser that the content of this page is accessible to certain origins. (An origin is a domain, plus a scheme and port number.) By default, Site B's pages are not accessible to any other origin; using the Access-Control-Allow-Origin header opens a door for cross-origin access by specific requesting origins.

For each resource/page that Site B wants to make accessible to Site A, Site B should serve its pages with the response header:

Access-Control-Allow-Origin: http://siteA.com Modern browsers will not block cross-domain requests outright. If Site A requests a page from Site B, the browser will actually fetch the requested page on the network level and check if the response headers list Site A as a permitted requester domain. If Site B has not indicated that Site A is allowed to access this page, the browser will trigger the XMLHttpRequest's error event and deny the response data to the requesting JavaScript code.

You'll probably want a cors npm package:

From the command like install cors:

npm install cors

Then in your API.js:

const axios = require ("axios");
const querystring = require('querystring');
const cors = require('cors')
app.use(cors())

export function getPeople(){
  return axios.get(`http://127.0.0.1:9000/people`)
}

export function postPeople(){
  axios.post('http://127.0.0.1:9000/people', querystring.stringify({
    'bar': 123
  }));
}
Dream_Cap
  • 2,292
  • 2
  • 18
  • 30
  • Would be like this? `export function postPeople(){ axios.post('http://127.0.0.1:9000/people', cors(), querystring.stringify({ 'bar': 123 })); }` – Jota Apr 21 '18 at 00:42
  • 1
    @Jota No, you need `cors()` on the server side not the client side. In any case, the problem is that you're only listening for `GET` requests on path `/people`, you'll have to add `app.post(....)` on the server side. – Titus Apr 21 '18 at 00:44
  • @Jota, I updated the code to what I think it should be. – Dream_Cap Apr 21 '18 at 00:45
1

You are getting CORS errors because you're trying to make requests to a different port (which counts as a different domain). You could set up CORS headers as seen in the other answer, but:

A much better way is to use a proxy in your react app. See Proxying API Requests if you are using create-react-app.

Then you would use the same port and just prefix with a /api route:

axios.post('/api/people', querystring.stringify({
  'bar': 123
}));
Austin Greco
  • 32,997
  • 6
  • 55
  • 59