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?

10
  • Are you importing server-side code into your frontend? Commented Apr 21, 2018 at 0:31
  • Not, how i do this ? Commented Apr 21, 2018 at 0:32
  • There's nothing at 127.0.0.1:9000/people . You are getting a 404 error, which means the server didn't have anything to serve at that address. Have you tried opening that link directly? Commented Apr 21, 2018 at 0:33
  • @acdcjunior Yes, i open and see the JSON.. Commented Apr 21, 2018 at 0:34
  • 1
    The method Get is working.. Commented Apr 21, 2018 at 0:35

2 Answers 2

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
  }));
}
Sign up to request clarification or add additional context in comments.

3 Comments

Would be like this? export function postPeople(){ axios.post('http://127.0.0.1:9000/people', cors(), querystring.stringify({ 'bar': 123 })); }
@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.
@Jota, I updated the code to what I think it should be.
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
}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.