最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Axios Post Request is Not Working in React JS - Stack Overflow

programmeradmin2浏览0评论

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";
  }

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";
  }
Share Improve this question edited May 1, 2020 at 1:25 Abdullah Ch asked May 1, 2020 at 1:11 Abdullah ChAbdullah Ch 1012 gold badges3 silver badges9 bronze badges 2
  • 1 did you enable CORS in your backend? – Ahmed Khattab Commented May 1, 2020 at 1:14
  • I did but still I am getting net::ERR_CONNECTION_REFUSED – Abdullah Ch Commented May 1, 2020 at 1:23
Add a ment  | 

3 Answers 3

Reset to default 2

Seems like a CORS issue

Install that on your node server:

https://www.npmjs./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./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.

发布评论

评论列表(0)

  1. 暂无评论