简体   繁体   中英

Axios Post Request is Not Working in React JS

I have used Postman to send Post requests and they are working fine but when I try to use axios it is giving me this error.


createAnimeList.js:27
 Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:83)
xhr.js:178 POST http://localhost:4000/animes/add 
net::ERR_CONNECTION_REFUSED

This is my backend code

router.post("/add", async (req, res) => {
  console.log("Heeeere");
  console.log(req.body.animeName);
  var anime = new Animes({
    animeName: req.body.animeName,
  });
  anime = await anime.save();
  return res.send(anime);
});

Here is my React code where I am using Axios

onSubmit(event) {
    event.preventDefault();
    const anime = {
      animeName: this.state.animeName,
    };
        console.log(anime);

    axios
      .post("http://localhost:4000/animes/add", anime)
      .then((res) => console.log(res.data))
      .catch((err) => console.log(err));

    //window.location = "/anime";
  }

Seems like a CORS issue

Install that on your node server:

https://www.npmjs.com/package/cors

Here is a simple example of node server with CORS enabled using this lib.

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

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 
  80')
})

you need to enable CORS( Cross-Origin-Resoruce-Sharing)

you can either use the cors package

https://www.npmjs.com/package/cors

or this code

place this controller before every controller in your application

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*'); // to enable calls from every domain 
  res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE'); // allowed actiosn
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); 

  if (req.method === 'OPTIONS') {
    return res.sendStatus(200); // to deal with chrome sending an extra options request
  }

  next(); // call next middlewer in line
});

It's a CORS issue: You need to add the follow code in your backend:

const cors = require('cors');
const express = require('express');
const app = express();

app.use(cors({
   credentials:true,
   origin: ['http://localhost:PORT']
 }));

Inside origin array you need to insert those urls who are in the white list.

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