Issue
I am trying to use netlify lambda functions with create react app, and it is breaking my site.
The repo was made by running npx create-react-app my-app-name
, and is the standard create react app boilerplate.
File structure:
root-directory/package.json
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"lambda": "netlify-lambda serve src/lambda"
},
"devDependencies": {
"netlify-lambda": "^2.0.15"
}
root-directory/netlify.toml:
[build]
command = "npm build"
functions = "lambda"
publish = "build"
src/setupProxy.js:
const proxy = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
proxy("/.netlify/functions/", {
target: "http://localhost:9000/",
pathRewrite: {
"^/\\.netlify/functions": "",
},
})
);
};
src/lambda/dictionary.js:
exports.handler = (event, context, callback) => {
callback(null, {
statusCode: 200,
body: "hello world",
});
};
Now, when I try to run npm run start
, the app will not load.
The browser displays the error:
This site can’t be reachedlocalhost refused to connect.
When you run npm run lambda
and to to the url http://localhost:9000/.netlify/functions/dictionary
in the browser, the browser does display "hello, world" as expected.
Also, I am not able to use the netlify cli because when I try to install it, I get permission errors/ access denied, even when I use sudo. So, trying to get this non globally installed way to work.
Solution
I just had the same issue with the same approach with your setupProxy.js. Then I modified the setupProxy.js to below and it worked for me
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(createProxyMiddleware('/functions/', {
target: 'http://localhost:9000/',
pathRewrite: {
"^\\.netlify/functions": ""
}
}));
};
Answered By - Kevin Chan Answer Checked By - Robin (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.