简体   繁体   中英

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.

I am getting an error from cors despite all efforts.

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.

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

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.

Using

$ npm i cors

Require this in your server.js file.

const cors = require('cors')

For simple usage to enable all CORs you can simply add this to your server.js file.

app.use(cors())

Check out the Express docs for CORs here

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