Problem description
The blogger uses Express as the background while learning the Next application. The deployment is fine locally, but the following error occurs when the deployment is on the byte light service.
To solve the process
Attempt 1: The attempt is a cross-domain problem
When I encountered this error at the beginning, I judged that it might be a cross-domain problem, but later I checked that it was not, because if it was a cross-domain problem, the self-defined route could not be accessed successfully. However, I accessed the self-defined route successfully through Postman, indicating that it was not a cross-domain problem, and I had configured the following statement.
app.use(cors()); // Resolve cross-domain
Copy the code
Attempt 2: Change the path of the static resource
Since only static resources can’t be accessed, it may be the middleware that configured static resources. So I just found such a solution on the Internet, namely the following statement.
app.use(express.static(path.join(__dirname, 'build'.'public')));
Copy the code
Later, I consulted relevant engineers of Byte Light service. It turned out that path.join would concatenate strings, but there was no build folder in my path, so there was an error. I thought the two folders were juxtaposed, but they were concatenated.
Attempt 3: Change to an absolute path (final solution)
With the help of byte Light service engineers, I used absolute path to expose static resources, and this time it worked
Thanks to the engineers at Byte Light Services.
app.use(express.static(path.join(__dirname, 'public')));
Copy the code
Question why
When express publishes static resources, if you do not add an absolute path, you will search for them according to the location of node execution in cloud platform. Naturally, there will be a 404 error, but if you add an absolute path dirname, you will avoid this problem and directly find the absolute path of the resource.
The resources
- Provide static files in Express
- The difference between __dirname and./ in Node.js