I am trying to generate a static website using nuxt with Json server Fake api server. I am just trying to pre-poplulate the static site with data from the json server using npm run generate. Thanks for all help!
<script>
import axios from 'axios'
export default {
async asyncData() {
const { data } = await axios.get('http://localhost:4000/gallery')
return { gallery: data }
}
}
</script>
<template>
<section class="gallery-grid">
<nuxt-link
v-for="i in gallery"
:key="i.id"
:to="'/'+i.id">
<img
:src="['gallery/'] + i.src + ['.jpg']"
:alt="i.title">
</nuxt-link>
</section>
</template>
Related
JS 13 and inside my ReadMoreButton client component i push my article data using useRouter hook of NEXT.
Not i can not use useRouter hook inside NEXT.JS server component so here i fetch searchParams and fetch that data.
here problem is before rendering i am checking if searchParams are defined or not not if i check in development everything work fine it render data but in production mode it show page not found error even if data is correctly send.
when i run next build it give me following output Output
and i am running side in production mode using next start and it show page not found when i do /article?serchParamsData.
You can check my whole code here : https://github.com/ssiwach8888/Next.JS-News-App
i also deploy production build on Vercel but it also show same error.
I am using NEXT.JS 13 with typescript
# ReadMoreButton.tsx "First Control goes here."
"use client";
type Props = {
article: NewsData;
};
import { useRouter } from "next/navigation";
//For navigate to SSC
const ReadMoreButton = ({ article }: Props) => {
const router = useRouter();
const handleClick = () => {
const queryString = Object.entries(article)
.map(([key, value]) => `${key}=${value}`)
.join("&");
const url = `/article?${queryString}`;
router.push(url);
};
return (
<button
className="bg-orange-400 h-10 rounded-b-lg dark:text-gray-900 hover:bg-orange-500"
onClick={handleClick}
>
Read More
</button>
);
};
export default ReadMoreButton;
# Article.tsx "Then we navigate to this page."
type Props = {
searchParams?: NewsData;
};
import { notFound } from "next/navigation";
import LiveTimestamp from "../Components/LiveTimestamp";
import Link from "next/link";
const ArticlePage = ({ searchParams }: Props) => {
if (
(searchParams && Object.entries(searchParams).length === 0) ||
!searchParams
) {
return notFound();
}
const article: NewsData = searchParams;
return (
<article className="mt-6">
<section className="flex flex-col lg:flex-row pb-24 px-0 lg:px-10">
<img
src={article.image === "null" ? "/no-image.jpeg" : article.image}
alt={article.title}
className="h-50 max-w-md mx-auto md:max-w-lg lg:max-w-xl object-contain rounded-lg shadow-md"
/>
<div className="px-8">
<Link legacyBehavior href={article.url || ""}>
<a target="_blank">
<h1 className="headerTitle hover:underline cursor-pointer px-0 pb-2">
{article.title}
</h1>
</a>
</Link>
<div className="flex divide-x-2 space-x-4">
<h2 className="font-bold">
By: {article.author !== "null" ? article.author : "Unknown"}
</h2>
<h2 className="font-bold pl-4">Source: {article.source}</h2>
<p className="pl-4">
<LiveTimestamp
time={
article.published_at === "null" ? "" : article.published_at
}
/>
</p>
</div>
<p className="pt-4 text-lg">{article.description}</p>
</div>
</section>
</article>
);
};
export default ArticlePage;
You just need to put the article page in [bracket] to make it dynamic so next js can fetch all pages otherwise it would display blank----
change article folder to [article]
more reference https://nextjs.org/docs/routing/dynamic-routes
I have installed multiple times Flask-socketio on my mac, closely reading the instructions and installing the requirements (eventlet/gevent). Athough when i run my simple code to test, it either says that i have not imported the modules or show nothing until i open index.html in my browser where it then displays :
The client is using an unsupported version of the Socket.IO or Engine.IO protocols (further occurrences of this error will be logged with level INFO)
Here is my app.py code:
from flask import Flask
from flask_socketio import SocketIO, send
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hello'
socketio = SocketIO(app, cors_allowed_origins='*')
#socketio.on('message')
def handle(msg):
print("message: "+msg)
send(msg, bradcast=True)
if __name__ == '__main__':
socketio.run(app)
And here is my terminal window:
Here is my index.html code (if needed):
<html>
<head>
<title>Chat Room</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
var socket = io.connect('http://127.0.0.1:5000');
socket.on('connect', function() {
socket.send('User has connected!');
});
socket.on('message', function(msg) {
$("#messages").append('<li>'+msg+'</li>');
console.log('Received message');
});
$('#sendbutton').on('click', function() {
socket.send($('#myMessage').val());
$('#myMessage').val('');
});
});
</script>
<ul id="messages"></ul>
<input type="text" id="myMessage">
<button id="sendbutton">Send</button>
</body>
</html>
Thank you for your help
Check the Flask-SocketIO docs for information about version compatibility.
You have installed Flask-SocketIO version 5, so you need version 3 of the JavaScript client, but you have 1.4.8.
Use this CDN URL instead for version 3.0.5: https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.5/socket.io.min.js
Just to be simple and up to a point, I want to make a request the same way I would do it with CURL or Postman's GET. For example:
curl https://www.google.com
gives
<!doctype html><html itemscope="" ... </body></html>
However, I am unable to do it with fetch, axios, request, nee...
All I want to do is to make a GET call (to https://www.google.com) in Vue.js and popup the alert(...); with a result.
How can I accomplish such a simple and a basic task ?
You can call fetch in a method.
Vue.config.devtools = false;
Vue.config.productionTip = false;
var app = new Vue({
el: '#app',
data: {
res: ""
},
methods: {
async get() {
const url = 'https://jsonplaceholder.typicode.com/todos/1';
this.res = await fetch(url).then(r => r.json());
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button #click="get">Fetch</button>
{{ res }}
</div>
I have learnt Nuxt JS and Spring MVC. I want to know, how to make a single page web application integrating or configuring Spring MVC and Nuxt JS. I didn't find any well documented material over internet. Basically, I want to handle all CRUD operations asynchronously. Database is MySQL. If possible, can someone help me how to do this? Thank you in advance!
I hope this will answer you, if I understand your question correctly.
Assuming, you have written the data access operations using Spring, Nuxt Js runs on port 3000, Tomcat on port 8080.
Let's say this is our RestController which fetches users data from database (using repository, service layer). Note the use of CrossOrigin - enabling cross origin request for restful web service which includes headers for Cross-Origin Resource Sharing (CORS) in the response. Here, we only allow localhost:3000 to send cross-origin requests. You can also go for Global CORS configuration.
#RestController
#RequestMapping("api")
#CrossOrigin(origins = "http://localhost:3000")
public class MainRestController {
private final IRestService restService;
#Autowired
public MainRestController(IRestService restService) {
this.restService = restService;
}
#GetMapping(value = "users", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Iterable<String>> getUsers() {
try {
return new ResponseEntity<>(restService.getAllUsers(), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
}
As you are using Nuxt js, this is our vue component which tries to access our REST end point which we created above. We are using axios to get our response here.
<template>
<div class="container">
<ul>
<li v-for="user of users">
{{user}}
</li>
</ul>
</div>
</template>
<script>
export default {
async asyncData({ $axios }) {
const users = await $axios.$get('http://localhost:8080/api/users');
return { users }
}
}
</script>
Your nuxt.config.js should contain this: the axios and proxy module should be installed.
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy'
],
axios: {
proxy: true,
},
env: {
baseUrl: process.env.BASE_URL || 'http://localhost:3000'
},
proxy: {
'/api/': {
target: 'http://localhost:8080/',
pathRewrite: { "^/api": "" },
changeOrigin: true,
}
},
i already have try to install mongodb via npm but i keep getting error Cannot find module "fs"
and my code is look like this
<script>
const MongoClient = require('mongodb').MongoClient;
export default {
data(){
return{
msg:'this is a test'
}
},
created:function(){
MongoClient.connect('mongodb://127.0.0.1:27017', (err, database) => {
if (err){
console.log('1');
}else{
console.log('2');
}
})
}
}
</script>
<template>
<div>
{{msg}}
</div>
</template>
so how do i import mongodb to my vuejs 2 framework?
VueJS is frontend framework.
You definitely should not try to deal with DB directly from Vue.
You should have backend made with any language/framework you want: NodeJS(if you want to stick with JS), ASP.NET(C#), Spring(Java) etc. and your backend should deal with DB and you should only make AJAX requests to your backend and send/get back JSONs and deal with JSONs on frontend with Vue.