Reputation: 114
The Strapi API responds the media URLs as something like "url:'/uploads/thumbnail.png'". I would like to get the complete URL that links to my file as value for "url". For example: "url:'https://example.org/uploads/thumbnail.png'"
The documentation also shows the full URL as response. How can I achieve this?
Upvotes: 3
Views: 9154
Reputation: 1
you can use this strapi plugin that prepend public url/media prefix to your media URL in api's URL
it converts the URLs from /uploads/thumbnail.png
to https://example.org/uploads/thumbnail.png
just
in response without changing the relative path in database
https://www.npmjs.com/package/strapi-plugin-media-prefix
Upvotes: 0
Reputation: 1807
Regarding Dallas answer, this modifies all URLs in the outgoing HTML to be full URLs containing the domain.
// File: resolveUrls.js
module.exports = (strapi) => {
return {
async initialize() {
strapi.app.use(async (ctx, next) => {
await next();
// Check if response type is HTML
const contentType = ctx.response.get('Content-Type');
if (contentType && contentType.includes('text/html')) {
const host = ctx.request.origin;
const body = ctx.body;
// Check if body is a string
if (typeof body === 'string') {
// Replace all relative URLs in the HTML with full URLs
const regex = /(?<=href="|src=")(?!https?:\/\/)(?!data:)(?!mailto:)([^"]+)/g;
ctx.body = body.replace(regex, `${host}/$1`);
}
}
});
},
};
};
This middleware checks if the response type is HTML and if so, retrieves the response body and the request origin. If the response body is a string, it uses a regular expression to find all relative URLs in the HTML and replaces them with full URLs containing the domain.
To use this middleware in Strapi, you can add it to the middlewares array in config/middleware.js:
// Add the resolveUrls middleware to the list of middlewares
resolveUrls: {
enabled: true,
// You can configure the middleware here, if needed
},
Upvotes: 0
Reputation: 4122
There are some potentials reasons why you shouldn’t store a full URL, and respond with a full URL. I won’t dive into those reasons.
I suggest creating the entire request/response, or creating a middleware component to intercept the response.
Then you can modify the original url value with the site’s URL. Looping through the results with something like:
const serverHost = strapi.config.get('server.host', 'defaultValueIfUndefined');
url = serverHost + url;
See the following docs for more details:
Upvotes: 0
Reputation: 114
The full URLs come from using an upload provider such as AWS-S3 or Cloudinary. The local provider doesn't support full URLs at the moment.
Upvotes: 3