简体   繁体   English

Axios 发布请求在 React JS 中不起作用

[英]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.我已经使用 Postman 发送 Post 请求并且它们工作正常但是当我尝试使用 axios 它给我这个错误。


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这是我使用 Axios 的 React 代码

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似乎是 CORS 问题

Install that on your node server:在您的节点服务器上安装它:

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

Here is a simple example of node server with CORS enabled using this lib.这是使用此库启用 CORS 的节点服务器的简单示例。

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)您需要启用 CORS(跨域资源共享)

you can either use the cors package您可以使用 cors package

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

or this code或此代码

place this controller before every controller in your application将此 controller 放在应用程序中的每个 controller 之前

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:这是一个 CORS 问题:您需要在后端添加以下代码:

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.在原始数组中,您需要插入那些在白名单中的 url。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM