Всем привет. Подскажите, пожалуйста, как решить следующую проблему.
Access to fetch at 'http://localhost:8080/feed/post' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Я отправляю данные на:
"http://localhost:8080/feed/post"
finishEditHandler = postData => {
this.setState({
editLoading: true
});
console.log('postData:', postData);
// Set up data (with image!)
const formData = new FormData();
formData.append("title", postData.title);
formData.append("content", postData.content);
formData.append("image", postData.image);
let url = "http://localhost:8080/feed/post";
let method = "POST";
// if (this.state.editPost) {
// url = 'URL';
// }
if (this.state.editPost) {
url = "http://localhost:8080/feed/post/" + this.state.editPost._id;
method = "PUT";
}
fetch(url, {
method: method,
body: formData,
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify({
// title: postData.title,
// content: postData.content
// })
})
.then(res => {
if (res.status !== 200 && res.status !== 201) {
throw new Error('Creating or editing a post failed!');
}
return res.json();
})
.then(resData => {
const post = {
_id: resData.post._id,
title: resData.post.title,
content: resData.post.content,
creator: resData.post.creator,
createdAt: resData.post.createdAt
};
this.setState(prevState => {
let updatedPosts = [...prevState.posts];
if (prevState.editPost) {
const postIndex = prevState.posts.findIndex(
p => p._id === prevState.editPost._id
);
updatedPosts[postIndex] = post;
} else if (prevState.posts.length < 2) {
updatedPosts = prevState.posts.concat(post);
}
return {
posts: updatedPosts,
isEditing: false,
editPost: null,
editLoading: false
};
});
})
.catch(err => {
console.log(err);
this.setState({
isEditing: false,
editPost: null,
editLoading: false,
error: err
});
});
};
Приложение у меня запущено на:
'http://localhost:3000'
Файл сервера выглядит следующим образом:
app.js
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const multer = require('multer');
const keys = require('./keys');
const feedRoutes = require('./routes/feed');
const app = express();
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'images');
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString() + '-' + file.originalname);
}
});
const fileFilter = (req, file, cb) => {
if (
file.mimetype === 'image/png' ||
file.mimetype === 'image/jpg' ||
file.mimetype === 'image/jpeg'
) {
cb(null, true);
} else {
cb(null, false);
}
};
// app.use(bodyParser.urlencoded()); // x-www-form-urlencoded <form>
app.use(bodyParser.json()); // application/json
app.use('/images', express.static(path.join(__dirname, 'images')));
app.use(
multer({storage: fileStorage, fileFilter: fileFilter}).single('image')
);
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
app.use('/feed', feedRoutes);
app.use((error, req, res, next) => {
console.log(error);
const status = error.statusCode || 500;
const message = error.message;
res.status(status).json({
message: message
});
});
mongoose
.connect(
keys.mongoURI
)
.then(result => {
console.log('MongoDB connected.');
app.listen(8080);
})
.catch(err => console.log(err));