I'm trying to implement the delete functionality for my survey creation app.
I'm using MongoDB with mongoose for the database, node.js/Express for the backend server and React/Redux for the frontend side.
Although I think I set routing correctly, I get 404 (Not Found) on axios.delete().
The error says that http://localhost:3000/api/surveys/delete/{the-survey-id-here} is not found.
I have been reading the documentation of axios, Express, mongoose and other websites, however, nothing worked for me.
I tried the following things.
Use findByIdAndRemove() instead of deleteOne()
Pass surveyId in the action creator const response = await axios.delete("/api/surveys", data: { surveyId });
Use <a></a> instead of <button></button>
Here are my codes.
SurveyList.js (react component which has the delete button)
import { fetchSurveys, deleteSurvey } from '../../actions'
...
<div className="card-action">
<a className="red-text text-accent-1">Yes: {survey.yes}</a>
<a className="red-text text-accent-1">No: {survey.no}</a>
<button
className="btn-floating btn-small waves-effect waves-light red right"
onClick={() => this.props.deleteSurvey(survey._id)}
>
<i className="material-icons">delete_forever</i>
</button>
</div>
...
const mapStateToProps = ({ surveys }) => {
return { surveys }
}
export default connect(
mapStateToProps,
{ fetchSurveys, deleteSurvey }
)(SurveyList)
actions/index.js (action creator)
export const deleteSurvey = (surveyId) => async dispatch => {
const response = await axios.delete(`/api/surveys/delete/${surveyId}`)
dispatch({ type: FETCH_SURVEYS, payload: response.data })
}
surveyRoute.js (routing handler)
app.delete('/api/surveys/delete/:surveyId', async (req, res) => {
await Survey.deleteOne({ _id: req.params.surveyId })
const surveys = await Survey.find({ _user: req.user.id }).select({
recipients: false
})
res.send(surveys)
})
server/index.js
const express = require('express')
const mongoose = require('mongoose')
const cookieSession = require('cookie-session')
const passport = require('passport')
const bodyParser = require('body-parser')
const keys = require('./config/keys')
require('./models/User')
require('./models/Survey')
require('./services/passport')
mongoose.connect(keys.mongoURI)
const app = express()
app.use(bodyParser.json())
app.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000, // milliseconds
keys: [keys.cookieKey]
})
)
app.use(passport.initialize())
app.use(passport.session())
require('./routes/authRoutes')(app)
require('./routes/billingRoutes')(app)
require('./routes/surveyRoutes')(app)
if(process.env.NODE_ENV === 'production'){
app.use(express.static('client/build'))
const path = require('path')
app.get('*',(req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
})
}
const PORT = process.env.PORT || 5000
app.listen(PORT)
In my case, leads/ is the end point. try your end point + survey id
With axios#^0.19.2
axios
.delete('/api/leads/' + id)
.then(res => {
dispatch({
type: DELETE_LEAD,
payload: id
});
So if I undestood correctly, you have a Expressjs App and a client app running on different ports, if so I think I found the issue
You are making ajax calls as if you had both frontend and backend running on the same server. Here are two possible solutions
Change the address of the Axios delete action to point to the right server if you are planning to run the backend and frontend on different servers
app.delete('http://localhost:5000/api/surveys/delete/:surveyId', async (req, res) => {
await Survey.deleteOne({ _id: req.params.surveyId })
const surveys = await Survey.find({ _user: req.user.id }).select({
recipients: false
})
res.send(surveys)
})
Off course you have to change the address once you deploy it to production and enable CORS
Build the client app for producion, this process will compile all css, js and html and save it to client/build folder as stated on line
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
This will cause the frontend and backend code to run on the same server
Thank you very much for all answers and comments. The problem was the proxy. I am using http-proxy-middleware to handle requests between different ports in the dev environment. All comments about ports made me realize that I need to check the 'setupProxy.js' file. I modified the code inside the file as below and that fixed the problem.
setupProxy.js
const proxy = require('http-proxy-middleware')
module.exports = function(app) {
app.use(proxy ('/auth/google', { target: 'http://localhost:5000' }))
app.use(proxy ('/api/**', { target: 'http://localhost:5000' }))
}
Thank you very much again for all the answers and comments.
CORS (Delete verb) must be enabled in your route middleware.
This thread may help you.
Related
I'm trying to build a instagram scraper with puppeteer and react that works with putting the username on an input and then I want to show the scraped data on the console, I already built the puppeteer script and It works, it returns the data correctly, But I have some issues trying to get the data from a post with axios, I'm using node js and express for my server, when I try to do the post with axios I keep getting an error.
I want to write the username on the input, then I want the puppeteer script to run, and then I want to console log the data that the puppeteer script returns
Error on console
POST http://localhost:4000/api/getData/username_im_scraping net::ERR_CONNECTION_REFUSED
This is my code
Server > index.js
const path = require("path");
const express = require("express");
const webpack = require("webpack");
const cors= require('cors');
const webpackDevMiddleware = require("webpack-dev-middleware");
const webpackHotMiddleware = require("webpack-hot-middleware");
const config = require(path.join(__dirname, "../webpack.config.js"));
const compiler = webpack(config);
const app = express();
const { script } = require("./script");
app.use(webpackDevMiddleware(compiler, config.devServer));
app.use(webpackHotMiddleware(compiler));
app.use(express.static(path.join(__dirname, '../build')));
app.use(cors());
app.get("/api/getData/:username", async (req, res) => {
console.log(`starting script for user ${req.params.username}`);
const data = await script(req.params.username);
console.log(`stopping script for user ${req.params.username}`);
res.send(data);
});
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, '../build', 'index.html'));
});
app.listen(process.env.PORT || 4000, () => {
console.log('Server is listening on port 4000');
});
Homepage.js
import React, { useState } from "react";
import axios from "axios";
const Homepage = props => {
const [username, setUsername] = useState("");
const onChange = ({ target: { value } }) => setUsername(value);
const onClick = () => {
axios.post('http://localhost:4000/api/getData/' + username, {
header: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;application/json' },
mode: "cors"
})
.then((response) => {
console.log(response);
})
.catch((error) => {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
})
};
return (
<div>
Time to start coding!
<input value={username} onChange={onChange} />
<button onClick={onClick}>Get instagram followers!</button>
</div>
);
};
export default Homepage;
The problem here is you defined your route with get like app.get("/api/getData/:username") but you are sending a post request. Either change the router to app.post or your axios method to axios.get.
UPDATE
Besides the changes above, after you shared the repository with me i checked and saw you have another problem, which was that you were not running your server so the ERR_CONNECTION_REFUSED message shown.
I forked your repository and made the following changes and created a PR for it. Please take a look at it, and if you want just merge it to your master branch.
P.S please for the next time create a .gitignore file and add node_modules to there so you don't push and pull your node_modules which takes some more amount of time.
I deployed my MERN project on heroku app but when I tried to submit my form it send me this error in console:
Access to XMLHttpRequest at 'localhost:8000/api/products' from origin
'https://thebeuter.herokuapp.com' has been blocked by CORS policy:
Cross origin requests are only supported for protocol schemes: http,
data, chrome, chrome-extension, https. Form.jsx:69 Error: Network
Error
at e.exports (createError.js:16)
at XMLHttpRequest.d.onerror (xhr.js:83)
Here is my server.js:
const express = require("express"),
app = express(),
cors = require("cors"),
port = process.env.PORT || 8000,
db = "beuter",
path = require("path"),
server = app.listen(port, () => console.log(`Listening to on port ${port}`));
app.use(cors());
app.use(express.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static('beuter/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'beuter', 'build', 'index.html'));
})
}
console.log(port)
require("./server/config/database.config")(db);
require("./server/routes/product.route")(app);
and here is my Form.jsx:
const addProduct = (e) => {
e.preventDefault();
const product = {
title,
title_url,
price,
description1,
description2,
description3,
description4,
description5,
img_url1,
img_url2,
img_url3,
img_url4,
size,
size2,
fit,
fit2,
category,
};
axios
.post("localhost:8000/api/products", product)
.then((res) => {
if (res.data.errors) {
setErrors(res.data.errors);
} else {
navigate("/");
}
})
.catch((err) => console.log(err));
};
return (
...
...
...
)
How can I fix this?
Here is my project github:
https://github.com/nathannewyen/the-beuter
Thank you!
Updated:
ShopAllProducts.jsx:
useEffect(() => {
const fetchItems = async () => {
setLoading(true);
const res = await axios.get("http://localhost:8000/api/products");
setProducts(res.data);
setLoading(false);
};
document.title = `Shop - The Beuter`;
fetchItems();
}, [props]);
the answer for this question is to have env files for development and production
for development
create the file called .env.development in the root folder of your frontend app
in .env.development add this line
REACT_APP_BASE_URL="http:localhost:5000"
and in .env.production add another line as
REACT_APP_BASE_URL="https://algorithammer.herokuapp.com"
or your website (here i am showing the sample)
now make sure that you have a variable called baseURL as global variable
example:
authAPI.js (example)
exports.baseURL = process.env.REACT_APP_BASE_URL;
in Login.js (example)
import {baseURL} from "./authAPI.js"
axios
.post(`${baseURL}/login`, {
data: "sample data"
})
.then((res) => console.log(res))
.catch((err) => console.log(err));
dont forget to push the changes and deploy the heroku app again
I keep getting the following error on my graphql queries and not sure why:
POST body missing. Did you forget use body-parser middleware?
Am I doing something weird here? I have tried different recommendations with body-parser online, but still can't seem to fix it.
Server:
require('babel-polyfill')
const express = require('express')
const router = require('./middleware')
const expressStaticGzip = require('express-static-gzip')
const app = express()
const port = process.env.EXPRESS_PORT || 4000
const bodyParser = require('body-parser')
app.use(/\/((?!graphql).)*/, bodyParser.urlencoded({ extended: true }))
app.use(/\/((?!graphql).)*/, bodyParser.json())
app.use('/search/data', expressStaticGzip('public'))
app.use('/', router)
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
})
Router
const router = express.Router()
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
const { authorization = '' } = req.headers
const universalFetch = (url, opts = {}) => {
return fetch(url, {
...opts,
headers: {
...opts.headers,
authorization,
},
})
}
const request = createRpcClient(universalFetch)
const methods = {}
const catalog = Object.keys(methods).reduce((catalog, method) => {
catalog[method] = params => request(methods[method], params)
return catalog
}, {})
return { catalog, fetch: universalFetch }
},
})
router.use(bodyParser.json())
router.use(bodyParser.text({ type: 'application/graphql' }))
router.use('*', renderer)
server.applyMiddleware({ app: router })
In my particular case the client just missed "Content-type" header with 'application/json' value. After adding that the error message has dissapeared.
applyMiddleware already adds body-parser for the GraphQL endpoint -- there's no need to apply it again and doing so may be causing your issue.
Additionally, I would expect applyMiddleware to be called before router.use('*', renderer) -- otherwise, I would think the wildcard route would be used for /graphql as well?
I forgot the header content-type: application/json
This error also caused by incorrect json in the body or some other problems in the body, such as unnecessary wrong invisible chars. So check generated json for errors and what is actually presents in the request body.
This error can also be raised because the body is too large.
I got it with apollo-server-micro inside a custom api route of NextJs.
It can be fixed by calling the json function coming from micro before apollo gets the request :
import { json } from 'micro'
import { ApolloServer } from 'apollo-server-micro'
const server = new ApolloServer({/*config*/})
const raiseBodyLimit: (handler: NextApiHandler) => NextApiHandler = (
handler
) => async (req, res) => {
if (req.headers['content-type'] !== 'application/json') {
return handler(req, res)
}
await json(req, { limit: '1gb' }) // This is the trick to raise body limit
return handler(req, res)
}
export default raiseBodyLimit(
server.createHandler({
path: '/api/graphql',
})
)
I saw this in this apollo-server's github issue.
Here are some information to build an apollo server endpoint with next.js
if your api upload anything you need to add the
{
uploads:true
}
in middleware while using graphql
I'm just learning Express/React and I'm trying to get set up with routes and basic database connections. I suspect I'm missing something very simple. I've tried to boil it down to the following.
Backend
server.js:
require('dotenv').config({path: '../.env'});
const mysql = require('mysql');
const express = require('express');
const bodyParser = require('body-parser');
const port = process.env.PORT || 5000;
const app = express();
const router = express.Router();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const users = require('./routes/api/users');
app.use('/api/users', users);
const events = require('./routes/api/events');
app.use('/api/events', events);
const db = mysql.createConnection({
host: process.env.DB_HOST,
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD
});
db.connect(function(err) {
if (err) throw err;
console.log('MySQL Connected!');
})
app.listen(port, () => console.log(`Listening on port ${port}`));
/routes/api/events.js:
const express = require('express');
const router = express.Router();
// GET api/events
router.get('/', (req, res) => {
res.send({id: "1", name: "hi"});
});
module.exports = router;
Frontend
App.js:
import React, { Component } from 'react';
import EventList from './components/EventList';
class App extends Component {
render() {
return (
<div className="App">
<EventList/>
</div>)
}
}
export default App;
/components/EventList.js:
import React, { Component } from 'react';
import axios from 'axios';
class EventList extends Component {
constructor() {
super();
this.state = {
events: []
}
}
componentDidMount() {
axios.get('/api/events')
.then(events => {
this.setState({events: events.data})
})
.catch(err => console.log(err))
}
render() {
var events = this.state.events;
return (
<div>
<p>Events:</p>
<ul>
{ events.map(({ id, name }) => (
<li>{name}</li>
))}
</ul>
</div>
)
}
}
export default EventList;
The error I get is http://localhost:3000/api/events 500 (Internal Server Error). What am I missing? I have truly scoured all of the docs I can find, but I'm not quite getting it.
Edit
I haven't changed anything, but now I'm getting a 404 (Not Found) instead. I had been getting a 500 for awhile, so it wasn't a momentary fluke. I'm not sure what could have changed.
Update
It may help to know that the .env variables I'm pointing to are actually for a remote MySQL database (i.e., DB_HOST != localhost, but a remote URL). Eventually, I'd like to connect the GET call on the events route to that db, but since it doesn't work with what I have here I figured my first issue to solve was upstream. As noted in comments, the PORT var I'm loading in is 3306. When I start the server, it says it's listening on 3306 as expected.
I think you are running your server on port 5000 and front on port 3000. if you request events with http://localhost:5000/api/events instead of /api/events, you would get 200 status code with your json data.
// as is
axios.get('/api/events')
// to be
axios.get('http://localhost:5000/api/events')
You could try typing componentDidMount function like this.
componentDidMount = async () =>{
//like this
}
In addition, I would recommend making the GET ALL its own function so you could just invoke in the componentDidMount function. whenever you run another CRUD action it will automatically update your events for you and instead of setting state every time you can invoke the this.getEvents() again to update it that way.
componentDidMount = async () =>{
this.getEvents()
}
Also you need to add this package (npm install cors) its so you can connect your api to your frontend.
Import it like this in your server.js file
const cors = require('cors')
app.use(cors())
You should add a proxy inside package.json in frontend like this.
"proxy": "http://localhost:5000",
Basically to summarize my problem: I have some image to be displayed and it's displayed on localhost:5000 with status 200 where my Express server is running and when it comes to localhost:3000 i.e. my React Development Server, I made a request using Axios and it does give me gibberish and I don't know how to handle it at all.
React Code:
componentDidMount() {
axios.get('/filesuploaded/video_______82395d6a5af4e98fb8efca56f0ae3c1b_____.jpeg')
.then(Response => console.log(Response))
.catch(err => console.log(err));
}
Express Code:
route.get('/:filename' , (req , res) => {
GridFS.files.findOne({filename: req.params.filename} , (err , file) => {
const readstream = GridFS.createReadStream(file.filename);
readstream.pipe(res);
})
});
Random Gibberish:
{data: "����..."
SOLUTION:
So I played around more with the code and I had forgotten that this existed in my package.json of my client side and I have used it to full potential and rewrote my server side code without using multer anywhere.
Package.json:
"proxy": "http://localhost:5000" //This helps React communicate with ExpressJS through ports.
Server Side Config:
const route = require('express').Router();
const mongoose = require('mongoose');
const GridFS = require('gridfs-stream');
//Route for getting files
route.get('/file/:id' , (req , res) => {
//Setting Up GridFS-Stream
const db = mongoose.connection.db;
const MongoDriver = mongoose.mongo;
const gfs = new GridFS(db , MongoDriver);
const readstream = gfs.createReadStream({
_id: req.params.id,
});
//Reading to Response
readstream.pipe(res);
});
module.exports = route;
Front End Config:
import React, { Component } from 'react'
export default class Files extends Component {
//Render Method
render() {
return (
<div>
<img src = {window.location.pathname} alt = "something" />
</div>
)
}
}
Here the window.location.pathname will translate to /file/:id and send a GET request to ExpressJS, hence loading the image!