简体   繁体   English

我在 Node js 中的 heroku 上收到 CORS 错误

[英]I am getting CORS error on heroku in Node js

I have deployed my blog app on heroku, I started with 2 folders api and client after that I put my client folder in api folder and delpoyed on heroku.我已经在 heroku 上部署了我的博客应用程序,我从 2 个文件夹 api 和 client 开始,然后我将我的 client 文件夹放在 api 文件夹中并在 heroku 上进行了 delpoyed。

I am getting an error from cors despite all efforts.尽管付出了所有努力,但我还是从 cors 那里得到了一个错误。

Can you let me know what am i doing wrong你能告诉我我在做什么错吗

Access to XMLHttpRequest at 'https://blogapi556.herokuapp.com/api/posts' from origin 'https://blogapp556.herokuapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Server Js looks like this.服务器 Js 看起来像这样。

const express = require("express");
const app = express();
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const authRoute = require("./routes/auth");
const userRoute = require("./routes/users");
const postRoute = require("./routes/posts");
const categoryRoute = require("./routes/categories");
const multer = require("multer");
const path = require("path");
let port = process.env.PORT || 5000;
dotenv.config();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  next();
});
app.use(express.json());
app.use("/images", express.static(path.join(__dirname, "/images")));
  
mongoose
  .connect(process.env.MONGO_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  })
  .then(console.log("Connected to MongoDB"))
  .catch((err) => console.log(err));
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "images");
  },
  filename: (req, file, cb) => {
    cb(null, req.body.name);
  },
});

const upload = multer({ storage: storage });
app.post("/api/upload", upload.single("file"), (req, res) => {
  res.status(200).json("File has been uploaded");
});
app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);
app.use("/api/posts", postRoute);
app.use("/api/categories", categoryRoute);

app.use(express.static(path.join(__dirname, "/client/build")));

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '/client/build', 'index.html'));
});


app.listen(port, () => {
  console.log("Backend is running.");
});

The request in client looks like this客户端中的请求如下所示

  const fetchPosts = async () =>{
    const res = await axiosInstance.get("/posts" + search);
    console.log(res);
setPosts(res.data)
  }

Axios Config File like this像这样的 Axios 配置文件

import axios from "axios"

 const axiosInstance = axios.create({
    baseURL: "https://blogapi556.herokuapp.com/api/",
})

axiosInstance.defaults.headers.common['Access-Control-Allow-Origin'] = '*';


export {axiosInstance}

You need to install the CORs NPM package.您需要安装 CORs NPM 包。

Using使用

$ npm i cors

Require this in your server.js file.在你的server.js文件中需要这个。

const cors = require('cors')

For simple usage to enable all CORs you can simply add this to your server.js file.对于启用所有 COR 的简单用法,您只需将其添加到server.js文件中即可。

app.use(cors())

Check out the Express docs for CORs here在此处查看 COR 的 Express 文档

暂无
暂无

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

相关问题 我在 NodeJS 上没有收到任何 CORS 错误(适用于 Node),但在获取 API 时在 React 和 Javascript 上收到错误 - I am not getting any CORS error on NodeJS (Works Fine with Node) but I am getting the error on React and Javascript while fetching API 我在需要堆栈的节点 js 中遇到错误 - I am getting a error in node js which is of Require Stack 我收到此错误: Block is not a constructor in node.js - I am getting this error: Block is not a constructor in node.js UnhandledPromiseRejectionWarning:未处理的承诺拒绝错误,我正在使用 Node JS 和 mongo Db - UnhandledPromiseRejectionWarning: Unhandled promise rejection error I am getting I am using Node JS and mongo Db 为什么在一种情况下我在ExpressJS中出现cors错误,而在另一种情况下却没有? - Why am I getting an error with cors in ExpressJS in one case, but not the other? 反应节点快递应用程序 - Heroku CORS 错误 - React node express app - Heroku CORS error 我收到一个node.js module.js:473错误消息 - I am getting a node.js module.js:473 error message http 错误 CORS 节点 JS - http error CORS Node JS 我的服务器已启动,但是当我尝试连接它时,出现错误[Node.js] - My Server is up but when I try to connect to it I am getting an error [Node.js] 当我尝试在“node.js”中运行这行代码时,我收到以下错误 - When I try to run this line of code in “node.js”, I am getting the following error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM