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

问题描述 投票:1回答:3

我已经使用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

这是我的后端代码

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

这是我正在使用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";
  }
javascript node.js reactjs axios restful-url
3个回答
1
投票

您需要启用CORS(跨域,重新共享资源)

您可以使用cors软件包

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

或此代码

将此控制器放置在应用程序中的每个控制器之前

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

2
投票

似乎是CORS问题

在节点服务器上安装:

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

这是使用此库启用了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')
})

0
投票

这是CORS问题:您需要在后端添加以下代码:

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

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

在原始数组内部,您需要插入白名单中的那些URL。

© www.soinside.com 2019 - 2024. All rights reserved.